如何在Java中将循环增加2等同于此:
for (int i = 0; i < max; i+=2)
现在我在Scala有:
for (a <- 0 to max)
对于事实max
将始终是平等的。我不知道如何在每个循环中将计数器增加到2。
答案 0 :(得分:60)
尝试for (a <- 0 until max by 2)
答案 1 :(得分:13)
请注意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
答案 2 :(得分:3)
这样你就可以像sc 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
答案 3 :(得分:1)
不出所料容易:
scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
答案 4 :(得分:1)
for (a <- 0 to max by 2) yield a
答案 5 :(得分:1)
当然
(0 until max by 2) foreach {...}
就足够了。