Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/chen18677338530/article/details/91443104
Introduction circulation branch
The first cycle way
object Demo9 {
def main(args: Array[String]): Unit = {
var start = 1
var end = 10
for (i <- start to end){
println(i)
}
}
}
object Demo10 {
def main(args: Array[String]): Unit = {
var list = List("too","foo")
for (i <- list){
println(i)
}
}
}
The second round-robin fashion
object Demo11 {
def main(args: Array[String]): Unit = {
for (i <- 1 until 3){
println(i)
}
}
}
Chapter III cycle way
object Demo12 {
def main(args: Array[String]): Unit = {
for (i <- 1 to 3 if i != 2){
println(i)
}
}
}
Introduce Variable
object Demo13 {
def main(args: Array[String]): Unit = {
for (i <- 1 to 3; j = 4 - i){
println(j)
}
}
}
Nested loop
object Demo14 {
def main(args: Array[String]): Unit = {
for (i <- 1 to 3; j <- 1 until 3){
println("i:"+i +",j:"+j)
}
}
}
The return value cycle
object Demo15 {
def main(args: Array[String]): Unit = {
var res = for (i <- 1 to 10) yield {
if (i % 2 == 0){
i
} else {
"不是偶数"
}
}
println(res)
}
}
Loop control step
object Demo16 {
def main(args: Array[String]): Unit = {
for (i <- 1 to 10){
println(i)
}
println("--------")
for (i <- Range(1,10,2)){
println(i)
}
println("--------")
for (i <- 1 to 10 if i % 2 == 1){
println(i)
}
}
}