2

Please let me know how can I add two if clause in a for loop with or option. for (name <- names **(if name.startsWith("S") || if name.endsWith("B".toLowerCase()) ) ) println(name)**

object ScalaList {
    def main(args: Array[String]): Unit = {
      val x = List(1,2,3,4,5)
      val x1 =List.range(10, 20)
      val x2 = 1::2::33::44::Nil
      val x3 = 100 :: x //(Prepending 100 in List x)
      val x4 = x1 ::: x2  //(Merging two list)
      val x5 = List.concat(x1 ,x2) //(Merging two list)

      x5.foreach {println} //Iterating list
      var sum=0
      var k = x.foreach (sum += _)

      val names =List("Sanjeeb","Hari","Adu","Bob")
      for (name <- names) println(name)
      for (name <- names if name.startsWith("S")                // <-- here is my if
          if name.endsWith("B".toLowerCase())  ) println(name)  // <-------


    }

}
2
  • Your question isn't clear enough. What is it you want this code to do? What error did you get from the compiler? At first blush, it looks like some { and } could help here. Commented Nov 30, 2014 at 16:13
  • Hello,I just want to add 2 if condition in For Loop. for (name <- names (if name.startsWith("S") || if name.endsWith("B".toLowerCase()) ) ) println(name) I need those person starting with S or ending with b. Is it clear sir. Commented Nov 30, 2014 at 16:44

2 Answers 2

3

Use braces:

for {
  name <- names 
  if name.startsWith("S")
  if name.endsWith("B".toLowerCase())
} {
  println(name)
}

It makes for nice notation when you have multiple things you're iterating over or multiple ifs or those things mixed together.

A semicolon between the ifs would also work:

for (name <- names if name.startsWith("S"); if name.endsWith("B".toLowerCase())) println(name)
Sign up to request clarification or add additional context in comments.

1 Comment

When you write two if statement (Line after Line) Is is referring to and clause or OR clause. I mean to ask your statements means name.startsWith("S") && name.endsWith("B".toLowerCase()) ????
1

You really needs two ifs ?

if (name.startsWith("S") || name.endsWith("B".toLowerCase())

2 Comments

Can you please help me in below comand. While executing in eclipse below output is coming.var temp = "sanjeeb|panda" println(temp.split("\\|")) [Ljava.lang.String;@c8ec3bc
Result of split function is string array String[]. In Java I would use Arrays.toString(temp)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.