Scala--循环

1、for循环

    //to [] 闭区间
    //for ( x<- 1 to 10) println(x);
    //until [)左闭右开区间
    for(x<- 1 until  10) println(x);

2、Scala没有break和continue,可以使用Breaks对象的break()方法

import util.control.Breaks._

object helloworld {

  def main(args: Array[String]) {

    breakable(
      for (x<-1 to 10 ){
        println(x);
        if(x==5) break;
      }
    )

3、双层for循环

import util.control.Breaks._

object helloworld {

  def main(args: Array[String]) {

    for(**i<-3 to 5;j<-1 to 4)**{
      printf("i=%d,j=%d,result=%d",i,j,i*j);
      println();
    }

  }
}

添加循环体的控制条件(守卫条件)

import util.control.Breaks._

object helloworld {

  def main(args: Array[String]) {

    for(i<-1 to 3;j<-1 to 4;***if i!=j***){
      printf("i=%d,j=%d,result=%d",i,j,i*j);
      println();
    }
  }
}

4、yield 生成一个新的数组向量

欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
原文地址:https://www.cnblogs.com/flyingcr/p/10327113.html