1、for语句直接循环
for (i <- 1 to 10) println("Value of i: " + i)
输出:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10
/**
* for语句开区间[1,10)
*/
for(i <- 1 until 10) println("Value of i: " + i)
输出:
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
2、for语句多区间循环
/**
* 多区间循环
* java 方式:
* for(int a = 1 ;a <= 3 ; a ++){
* for(int b = 1 ;b <= 4 ; b ++){
* System.out.println("Value of a: " + a);
* System.out.println("Value of b: " + b)
* }
* }
*/
for(a <- 1 to 3; b <- 1 to 4){
println( "Value of a: " + a );
println( "Value of b: " + b );
}
输出:
Value of a: 1
Value of b: 1
Value of a: 1
Value of b: 2
Value of a: 1
Value of b: 3
Value of a: 1
Value of b: 4
Value of a: 2
Value of b: 1
Value of a: 2
Value of b: 2
Value of a: 2
Value of b: 3
Value of a: 2
Value of b: 4
Value of a: 3
Value of b: 1
Value of a: 3
Value of b: 2
Value of a: 3
Value of b: 3
Value of a: 3
Value of b: 4
3、for语句多区间循环 后面的区间可以使用前面的区间变量a
for(a <- 1 to 3; b <- 0 to a){
println( "Value of a: " + a );
println( "Value of b: " + b );
}
输出:
Value of a: 1
Value of b: 0
Value of a: 1
Value of b: 1
Value of a: 2
Value of b: 0
Value of a: 2
Value of b: 1
Value of a: 2
Value of b: 2
Value of a: 3
Value of b: 0
Value of a: 3
Value of b: 1
Value of a: 3
Value of b: 2
Value of a: 3
Value of b: 3
4、for语句循环过滤,如果有多个条件使用;分开
val numList = List(1,2,3,4,5,6,7,8,9)
for(i <- numList if i < 6) println("Value of "+i)
输出:
Value of 1
Value of 2
Value of 3
Value of 4
Value of 5
5、for语句使用yield 来使for语句循环的返回值作为一个变量存储
val numList = List(1,2,3,4,5,6,7,8,9)
val retVal = for(i <- numList if i > 2; if i<4) yield i
for (i <- retVal) println("Value of "+i)
输出:
Value of 3