Scala 循環(打斷嵌套循環)

import scala.util.control._

object Test {
   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.
   }
}

當上述代碼被編譯和執行時,它產生了如下結果:oop

C:/>scalac Test.scala
C:/>scala Test
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

C:/>

使用嵌套循環打破現有循環。因此,若是有使用break嵌套循環,那麼上面的方式來進行。spa

 

loop.breakablescala

import scala.util.control._

object Test {
   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" );
   }
}

當上述代碼被編譯和執行時,它產生了如下結果:編譯

C:/>scalac Test.scala
C:/>scala Test
Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
After the loop

C:/>
相關文章
相關標籤/搜索