Scala break语句研究

xiaoxiao2021-02-28  82

简介

Scala语言提供了类似Java的循环语句,支持while循环,do...while循环,for循环。但不同的是Scala不支持break或continue语句。从Scala 2.8版本后提供了一种中断循环的方式,即支持Break类。本文将以两个例子来简单介绍Break类的使用方法。

语法

Scala中break的用法如下:

// 导入以下包 import scala.util.control._ //函数体 def func() { // 创建 Breaks 对象 val loop = new Breaks // 在 breakable 中循环 loop.breakable{ // 循环体 for(...){ .... // 循环中断 loop.break } } }

中断循环

下面的例子中将使用while循环来打印1到10的数字:

import scala.util.control._ object TestBreak { def main(args: Array[String]): Unit = { var a = 1 val loop = new Breaks loop.breakable { while (true) { if (a > 10) { loop.break } println("a = " + a) a += 1 } } } }执行此类,输出如下:

$ scala TestBreak.scala a = 1 a = 2 a = 3 a = 4 a = 5 a = 6 a = 7 a = 8 a = 9 a = 10

中断嵌套循环

下面的例子来打印99乘法表,使用了while和for循环。因为是嵌套循环,所以这里需要定义两个Break对象,分别管理内外两层循环语句的中断退出功能。

import scala.util.control._ object TestBreak { def main(args: Array[String]): Unit = { var a = 1 var b = 1 val inner = new Breaks var outer = new Breaks outer.breakable { //外部循环 while (true) { if (a > 9) { outer.break //外部中断 } inner.breakable { //内部循环体 for (b <- 1 to 9) { if (b > a) { inner.break //内部中断 } print(a + " x " + b + " = " + (a * b) + ";") } } println() a += 1 } } } }运行时输出结果如下:

$ scala TestBreak.scala 1 x 1 = 1; 2 x 1 = 2;2 x 2 = 4; 3 x 1 = 3;3 x 2 = 6;3 x 3 = 9; 4 x 1 = 4;4 x 2 = 8;4 x 3 = 12;4 x 4 = 16; 5 x 1 = 5;5 x 2 = 10;5 x 3 = 15;5 x 4 = 20;5 x 5 = 25; 6 x 1 = 6;6 x 2 = 12;6 x 3 = 18;6 x 4 = 24;6 x 5 = 30;6 x 6 = 36; 7 x 1 = 7;7 x 2 = 14;7 x 3 = 21;7 x 4 = 28;7 x 5 = 35;7 x 6 = 42;7 x 7 = 49; 8 x 1 = 8;8 x 2 = 16;8 x 3 = 24;8 x 4 = 32;8 x 5 = 40;8 x 6 = 48;8 x 7 = 56;8 x 8 = 64; 9 x 1 = 9;9 x 2 = 18;9 x 3 = 27;9 x 4 = 36;9 x 5 = 45;9 x 6 = 54;9 x 7 = 63;9 x 8 = 72;9 x 9 = 81;

转载请注明原文地址: https://www.6miu.com/read-59312.html

最新回复(0)