scala编写任意输入一个月份输出它所属的季节
时间: 2024-09-11 15:03:38 浏览: 69
scalua:LuaJ 的包装器,用 Scala 编写
在Scala中,你可以创建一个函数来判断给定的一个月份属于哪个季节。通常,我们把一年分为四个季度,每个季度三个月。以下是判断季节的基本步骤:
```scala
def getSeason(month: Int): String = {
val monthsInEachSeason = List(0 until 3, 3 until 6, 6 until 9, 9 until 12) // 每个季度的月份范围
for (seasonRange <- monthsInEachSeason) {
if (month >= seasonRange.head && month <= seasonRange.last) {
return "春季" if seasonRange == monthsInEachSeason(0)
return "夏季" if seasonRange == monthsInEachSeason(1)
return "秋季" if seasonRange == monthsInEachSeason(2)
return "冬季" if seasonRange == monthsInEachSeason(3)
}
}
throw new IllegalArgumentException(s"Month $month is not valid.")
}
// 示例用法
val month = 7 // 七月
val season = getSeason(month)
println(s"In $month, the season is ${season}.")
```
阅读全文