练习

36 阅读1分钟

4. 编写一个函数,允许用户输入一个整数年份,如果用户输入的是闰年就停止输入,否则就一直提示用户输入。

import scala.io.StdIn

object Base28 {
  def main(args: Array[String]): Unit = {
    // 定义判断闰年的函数(复制第1题的逻辑)
    def isLeapYear(year: Int): Boolean = {
      (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
    }

    def inputUntilLeapYear(): Unit = {
      var year = 0
      do {
        print("请输入年份:")
        year = StdIn.readInt()
      } while (!isLeapYear(year)) // 注意:条件是“不是闰年则继续循环”,所以用!isLeapYear
      println(s"输入的闰年是:$year")
    }

    // 调用函数执行逻辑
    inputUntilLeapYear()
  }
}