Scala编程

Scala编程详解02:条件控制与循环

2020-05-25  本文已影响0人  勇于自信
1. if表达式
2. 语句终结符、块表达式
3.输入和输出
object scala_demo01 {
  def main(args: Array[String]): Unit = {
    val name = readLine("Welcome to Game House. Please tell me your name: ")
    print("Thanks. Then please tell me your age: ")
    val age = readInt()
    if(age > 18) {
      printf("Hi, %s, you are %d years old, so you are legel to come here!", name, age)
    } else {
      printf("Sorry, boy, %s, you are only %d years old. you are illegal to come here!", name, age)
    }

  }
}

运行如下:


4. 循环
import scala.util.control.Breaks._
object scala_demo02 {
  def main(args: Array[String]): Unit = {
    breakable {
      var n = 10
      for(c <- "Hello World") {
        if(n == 5) break;
        println(c)
        n -= 1
      }
    }

  }
}

打印:

H
e
l
l
o
5.高级for循环
for(i <- 1 to 9; j <- 1 to 9) {
  if(j == 9) {
    println(i * j)
  } else {
    print(i * j + " ")
  }
}

输出:


for(i <- 1 to 100 if i % 2 == 0) println(i)

·for推导式:构造集合

for(i <- 1 to 10) yield i
上一篇下一篇

猜你喜欢

热点阅读