请告诉我如何在for循环中添加两个if子句或选项。 for(name< - names **(如果name.startsWith(" S")|| 如果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) // <-------
}
}
答案 0 :(得分:2)
使用大括号:
for {
name <- names
if name.startsWith("S")
if name.endsWith("B".toLowerCase())
} {
println(name)
}
当你有多个迭代的东西或多个if
或混合在一起的东西时,它会很好用。
if
之间的分号也可以起作用:
for (name <- names if name.startsWith("S"); if name.endsWith("B".toLowerCase())) println(name)
答案 1 :(得分:1)
你真的需要两个if
s?
if (name.startsWith("S") || name.endsWith("B".toLowerCase())