Scala cycle control

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

Here Insert Picture Description

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)
    }
  }
}

Here Insert Picture Description

object Demo10 {
  def main(args: Array[String]): Unit = {
    var list = List("too","foo")
    for (i <- list){
      println(i)
    }
  }
}

Here Insert Picture Description

The second round-robin fashion

object Demo11 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 until 3){
      println(i)
    }
  }
}

Here Insert Picture Description

Chapter III cycle way

object Demo12 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 3 if i != 2){
      println(i)
    }
  }
}

Here Insert Picture Description

Introduce Variable

object Demo13 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 3; j = 4 - i){
      println(j)
    }
  }
}

Here Insert Picture Description

Nested loop

object Demo14 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 3; j <- 1 until 3){
      println("i:"+i +",j:"+j)
    }
  }
}

Here Insert Picture Description

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)
  }
}

Here Insert Picture Description

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)
    }
  }
}

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/chen18677338530/article/details/91443104