Scala break语句

Scala中没有内置的break语句,但是如果您运行的是Scala 2.8版本,则可以使用break语句。当循环中遇到break语句时,循环将立即终止,程序控制跳到循环之后的下一个语句执行。

流程图

语法

以下是break语句的语法 -

// import following package
import scala.util.control._

// create a Breaks object as follows
val loop = new Breaks;

// Keep the loop inside breakable as follows
loop.breakable {
   // Loop will go here
   for(...){
      ....

      // Break will go here
      loop.break;
   }
}

尝试以下示例程序来理解break语句。

import scala.util.control._

object Demo {
   def main(args: Array[String]) {
      var a = 0;
      val numList = List(1,2,3,4,5,6,7,8,9,10);

      val loop = new Breaks;

      loop.breakable {
         for( a <- numList){
            println( "Value of a: " + a );

            if( a == 4 ){
               loop.break;
            }
         }
      }
      println( "After the loop" );
   }
}

将上述程序保存在源文件:Demo.scala 中,使用以下命令编译和执行此程序。

$ scalac Demo.scala
$ scala Demo

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
After the loop

中断嵌套循环

在使用嵌套循环时,存在一个问题。为了防止对嵌套循环使用break,请参照下面的方法。这是一个中断嵌套循环的示例程序。

示例

import scala.util.control._

object Demo {
   def main(args: Array[String]) {
      var a = 0;
      var b = 0;
      val numList1 = List(1,2,3,4,5);
      val numList2 = List(11,12,13);

      val outer = new Breaks;
      val inner = new Breaks;

      outer.breakable {
         for( a <- numList1){
            println( "Value of a: " + a );

            inner.breakable {
               for( b <- numList2){
                  println( "Value of b: " + b );

                  if( b == 12 ){
                     inner.break;
                  }
               }
            } // inner breakable
         }
      } // outer breakable.
   }
}

将上述程序保存在源文件:Demo.scala 中,使用以下命令编译和执行此程序。

扫描二维码关注公众号,回复: 3569515 查看本文章
$ scalac Demo.scala
$ scala Demo

Value of a: 1
Value of b: 11
Value of b: 12
Value of a: 2
Value of b: 11
Value of b: 12
Value of a: 3
Value of b: 11
Value of b: 12
Value of a: 4
Value of b: 11
Value of b: 12
Value of a: 5
Value of b: 11
Value of b: 12

猜你喜欢

转载自blog.csdn.net/love284969214/article/details/82930855