辽阳网站建设企业/网站排名优化公司哪家好
循环类型
Scala 语言提供了以下几种循环类型。点击链接查看每个类型的细节。
while
语法
while(condition)
{statement(s);
}
示例
object Test {def main(args: Array[String]) {// 局部变量var a = 10;// while 循环执行while( a < 20 ){println( "Value of a: " + a );a = a + 1;}}
}
输出:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do while
语法
do {statement(s);
} while( condition );
实例
object Test {def main(args: Array[String]) {// 局部变量var a = 10;// do 循环do{println( "Value of a: " + a );a = a + 1;}while( a < 20 )}
}
输出:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for
语法
for( var x <- Range ){statement(s);
}
实例
a to b
object Test {def main(args: Array[String]) {var a = 0;// for 循环for( a <- 1 to 10){println( "Value of a: " + a );}}
}
结果:
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
a until b
以下是一个使用了 i until j 语法(不包含 j)的实例:
object Test {def main(args: Array[String]) {var a = 0;// for 循环for( a <- 1 until 10){println( "Value of a: " + a );}}
}
结果:
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
结果里没有10
for 遍历多个集合
在 for 循环 中你可以使用分号 (;) 来设置多个区间,它将迭代给定区间所有的可能值。以下实例演示了两个区间的循环实例:
object Test {def main(args: Array[String]) {var a = 0;var b = 0;// for 循环for( a <- 1 to 3; b <- 1 to 3){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: 2
Value of b: 1
Value of a: 2
Value of b: 2
Value of a: 2
Value of b: 3
Value of a: 3
Value of b: 1
Value of a: 3
Value of b: 2
Value of a: 3
Value of b: 3
for 循环集合
语法:
for( var x <- List ){statement(s);
}
实例:
object Test {def main(args: Array[String]) {var a = 0;val numList = List(1,2,3,4,5,6);// for 循环for( a <- numList ){println( "Value of a: " + a );}}
}
结果:
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
for 循环过滤
Scala 可以使用一个或多个 if 语句来过滤一些元素。
以下是在 for 循环中使用过滤器的语法。
语法:
for( var x <- Listif condition1; if condition2...){statement(s);
实例
object Test {def main(args: Array[String]) {var a = 0;val numList = List(1,2,3,4,5,6,7,8,9,10);// for 循环for( a <- numListif a != 3; if a < 8 ){println( "Value of a: " + a );}}
}
结果:
value of a: 1
value of a: 2
value of a: 4
value of a: 5
value of a: 6
value of a: 7
for 使用 yield
你可以将 for 循环的返回值作为一个变量存储。语法格式如下:
语法:
var retVal = for{ var x <- Listif condition1; if condition2...
}yield x
实例:
object Test {def main(args: Array[String]) {var a = 0;val numList = List(1,2,3,4,5,6,7,8,9,10);// for 循环var retVal = for{ a <- numList //retVal是一个存储变量if a != 3; if a < 8}yield a// 输出返回值for( a <- retVal){println( "Value of a: " + a );}}
}
结果
value of a: 1
value of a: 2
value of a: 4
value of a: 5
value of a: 6
value of a: 7