如何将循环增加 2 与 Java 中的等效:
for (int i = 0; i < max; i+=2)
现在在 Scala 我有:
for (a <- 0 to max)
因为事实max
永远是平的。我不知道如何在每个循环中将计数器增加到 2。
尝试for (a <- 0 until max by 2)
to
注意和之间的区别until
。严格i < max
要求,直到。
val max = 10
scala> for(i <- 0 until max by 2)
| println(i)
0
2
4
6
8
scala> for(i <- 0 to max by 2)
| println(i)
0
2
4
6
8
10
这样你就可以像 java one 一样使用 scala for 循环。
object Example extends App {
for(i <-0 to 20 by 2) {
println("Value of i = "+ i)
}
}
输出
Value of i = 0
Value of i = 2
Value of i = 4
Value of i = 6
Value of i = 8
Value of i = 10
Value of i = 12
Value of i = 14
Value of i = 16
Value of i = 18
Value of i = 20
一定
(0 until max by 2) foreach {...}
就足够了。
不出所料的容易:
scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
for (a <- 0 to max by 2) yield a