5.2.1.3 退出循环

在 Scale 中没有提供break, continu 这两个会打破循环流程的关键字. 估计是因为 Scala 的发明人认为这两个关键字不够面向对象和函数式.

那么如何退出循环呢?

有 3 种方式可以退出循环:

  1. 循环守卫(推荐)
  2. 使用Breaks对象中的break方法

  3. 使用嵌套函数. --- 在函数中使用return语句. 这种方式大家都比较好理解: 函数都结束了, 循环自然就结束了.

1. 循环守卫

循环守卫的意思就是在循环中加入条件表达式.

例如:

package com.atguigu.day02

object ForDemo4 {
  def main(args: Array[String]): Unit = {
    // 输出1 - 10之间的偶数

    for (i <- 1 to 10 if (i % 2 == 0)) { // if... 就叫循环守卫
      print(i + " ")
    }
  }

}

注意:

  • 循环守卫是类似于 Java 中的 continue 的存在, 当if中的条件是false的时候, 并不是结束整个循环.

那么如何彻底的不再执行循环中的代码? 需要使用一个boolean型的变量来配合:

package com.atguigu.day02

object ForDemo5 {
  def main(args: Array[String]): Unit = {
    var bound = false
    for (i <- 1 to 10 if !bound) {
      if(i >= 5) {
        bound = true
      }else{
        print(i + " ")
      }
    }
  }

}

2. Breaks对象中的break方法

package com.atguigu.day02

import scala.util.control.Breaks

object ForDemo5 {
  def main(args: Array[String]): Unit = {

    for (i <- 1 to 10) {
      if(i >= 5){
        Breaks.break()
      } else {
        print(i + " ")
      }
    }
    println("循环结束了")
  }

}

怎么让循环后面的代码也要执行吗?

捕捉异常!

Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-07-02 08:12:45

results matching ""

    No results matching ""