在 Scala 中将 for 循环增加 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17791464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment for-loop by 2 in Scala
提问by cYn
How do I increment the loop by 2 as equivalent to this in Java:
如何将循环增加 2 相当于 Java 中的这个:
for (int i = 0; i < max; i+=2)
Right now in Scala I have:
现在在 Scala 我有:
for (a <- 0 to max)
For a fact maxwill always be even. I don't know how to increment the counter to 2 in each loop.
因为事实max永远是偶数。我不知道如何在每个循环中将计数器增加到 2。
回答by tkroman
Try for (a <- 0 until max by 2)
尝试 for (a <- 0 until max by 2)
回答by Brian
Note the difference between toand until. With a strict i < maxyou will want until.
注意之间的差异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
回答by Nilesh Shinde
This way you can use scala for loop like java one.
这样你就可以像java one一样使用scala for循环。
object Example extends App {
for(i <-0 to 20 by 2) {
println("Value of i = "+ i)
}
}
Output
输出
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
回答by om-nom-nom
Unsurprisingly easy:
出乎意料的简单:
scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
回答by Vorsprung
for (a <- 0 to max by 2) yield a
回答by claydonkey
Surely
一定
(0 until max by 2) foreach {...}
will suffice.
就足够了。

