5.2.1.5 循环嵌套

package com.atguigu.day02

object ForDemo7 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 9; j <- 1 to i) {
      print(j + " * " + i + " = " + i * j + "\t");
      if (j == i) println
    }
  }
}

等价于下面的代码:

package com.atguigu.day02

object ForDemo7 {
  def main(args: Array[String]): Unit = {
    for (i <- 1 to 9) {
      for (j <- i to 9) {
        print(j + " * " + i + " = " + i * j + "\t");
      }
      println
    }
  }
}

多了解一点:

其实for() 这里的圆括号()可以使用{ }来替换掉, 这样里面分号就可以省略了(当你使用多行的时候, 如果仍然在一行, 则不能省略)

package com.atguigu.day02

object ForDemo7 {
  def main(args: Array[String]): Unit = {
    for {
      i <- 1 to 9  // 后面的分号可以省略了
      j <- 1 to i
    } {
      print(j + " * " + i + " = " + i * j + "\t");
      if (j == i) println
    }

  }
}
Copyright © 尚硅谷大数据 2019 all right reserved,powered by Gitbook
该文件最后修订时间: 2019-07-02 08:12:45

results matching ""

    No results matching ""