42

如何将循环增加 2 与 Java 中的等效:

for (int i = 0; i < max; i+=2)

现在在 Scala 我有:

for (a <- 0 to max)

因为事实max永远是平的。我不知道如何在每个循环中将计数器增加到 2。

4

6 回答 6

77

尝试for (a <- 0 until max by 2)

于 2013-07-22T15:26:56.110 回答
22

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
于 2013-07-22T15:26:57.723 回答
3

这样你就可以像 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
于 2017-11-07T10:19:37.240 回答
2

一定

(0 until max by 2)  foreach {...}

就足够了。

于 2016-10-23T11:24:57.910 回答
1

不出所料的容易:

scala> for (a <- 0 until 10 by 2) yield a
// Vector(0, 2, 4, 6, 8, 10)
于 2013-07-22T15:27:38.303 回答
1
for (a <- 0 to max by 2) yield a
于 2013-07-22T15:30:23.897 回答