045_循环的注意事项和练习题
package com.atguigu.chapter04.myfor
object usefor2 {
def main(args: Array[String]): Unit = {
for (i <- 1 to 3; j = i * 2) {
println(" i= " + i + " j= " + j)
}
//等价
println("------------------------")
for {
i <- 1 to 3
j = i * 2} {
println(" i= " + i + " j= " + j)
}
}
}
注意事项
package com.atguigu.chapter04.myfor
object stepfor {
def main(args: Array[String]): Unit = {
for (i <- 1 to 10) {
println("i=" + i)
}
//步长控制为2
println("---------------------")
//Range(1,10,2)的对应的构建方法是
//def apply(start: Int, end: Int, step: Int): Range = new Range(start, end, step)
for (i <- Range(1, 10, 2)) {
println("i=" + i)
}
//控制步长的第二种方式-for循环守卫.
// 不用range() 也可以控制
// 使用 取模 %
println("---------------------")
for (i <- 1 to 10 if i % 2 == 1) {
println("i=" + i)
}
}
}
这种步长不就是python的写法么
package com.atguigu.chapter04.myfor
object ForExercise01 {
def main(args: Array[String]): Unit = {
/*
for循环练习题
打印1-100之间所有是9的倍数的整数的个数及总和
完成下面的表达式输出
*/
val start = 1
val end = 100
var count = 0
var sum = 0
for (i <- start to end) {
if (i % 9 == 0) {
count += 1
sum += i
}
}
printf("count=%d, sum=%d\n", count, sum)
//输出加法循环表达式吧
val num = 6
for (i <- 0 to num) {
printf("%d + %d = %d\n", i, (num - i), num)
}
var list = List(1,2)
}
}
count=11, sum=594
0 + 6 = 6
1 + 5 = 6
2 + 4 = 6
3 + 3 = 6
4 + 2 = 6
5 + 1 = 6
6 + 0 = 6
Process finished with exit code 0