Scala-循环

package com.mengyao.scala.function

/**
 * Scala中循环的声明和使用(while和for)
 *
 * @author mengyao
 */
object Test3 {
 
  def main(args: Array[String]){
    
    test1
    
    test2
    
    test3
    
    test4
    
    test5
    
    test6
    
    test7
    
    test8
    
    test9
  }
 
  //while循环0到10
  def test1(): Unit = {
    var count = 0;
    while(true){
      println(count)
      count+=1
      if(count>10)
        return
    }
  }
 
  //输出从1到3
  def test2(): Unit = {
      for(i<-1 to 3){    // 实际上是调用1.to(3)方法,scala把所有都视为对象(数字1是RichInt类的方法,这个类型是由Int隐式转换来的。to()方法返回的是一个Range类的实例)
          print(i+",")     // 不换行输出。注意i是一个val常量,不是var变量。每次循环都创建一个叫做i的val常量,不可以在循环中改变常量i的值。
      }    
  }
 
  //输出从1到2,until方法不包含最后一个值
  def test3(): Unit = {
      for(i<-1 until 3){ // 实际上是调用1.until(3)方法,scala把所有都视为对象(数字1是RichInt类的方法,这个类型是由Int隐式转换来的。until()方法返回的是一个Range类的实例)
          print(i+",")     // 不换行输出。注意i是一个val常量,不是var变量。每次循环都创建一个叫做i的val常量,不可以在循环中改变常量i的值。
      }    
  }
 
  //输出从1到3
  def test4(): Unit = {
      (1 to 3).foreach(i=>print(i+",")) // 使用Range类的foreach()方法,foreach()方法接收的的参数是一个函数值,所以需要在括号中提供一段代码体    
  }
 
  //倒序输出从10到1
  def test5(): Unit = {
    for(i<-1 to 10 reverse){          // 使用Range类的reverse()方法,该方法会将一个数组倒序输出
      println(i)
    }
  }
 
  //倒序改变步长-守卫
  def test6(): Unit = {
    for(i <- 1 to 10 reverse ; if i%2==0) {
      println(i)
    }
  }
 
  //倒序改变步长
  def test7(): Unit = {
    for(i <- 1 to (10, 2)){
      println(i)
    }
  }
 
  //双重for循环
  def test8(): Unit = {
    for(i <- 1 to 10; j <- 1 to 10){
      println(i+" : "+j)
    }
    //或者如下
//    for(i <- 1 to 10){
//      for(j <- 1 to 10){
//        println(i+" : "+j)
//      }
//    }
  }
 
  //for的推导式
  def test9(): Unit = {
    val nums = for(i <- 1 to 10)yield {i+1}
    //或者如下
//    val nums = for(i <- 1 to 10)yield (i+1)
//    val nums = for(i <- 1 to 10)yield i+1
    println(nums)
  }
}

原文地址:https://www.cnblogs.com/mengyao/p/4890667.html