【发布时间】:2021-02-19 19:37:54
【问题描述】:
我正在尝试做一个温度程序,它输出提供的三个城市的最低温度。如果三个城市之一的温度高于 + 57 或低于 -92,则所有三个城市都将设置默认值(莫斯科 +5,河内 +20,迪拜为 30)
但是,在 readLine 中提供这些数字 20,100,35 是行不通的。
这就是City 类的样子:
class City(val name: String) {
var degrees: Int = 0
set(value) {
field =
if (value > 57 || -92 > value) {
when (this.name) {
"Dubai" -> 30
"Moscow" -> 5
"Hanoi" -> 20
else -> 0
}
} else {
value
}
}}
我主要有:
val first = readLine()!!.toInt()
val second = readLine()!!.toInt()
val third = readLine()!!.toInt()
val firstCity = City("Dubai")
val secondCity = City("Moscow")
val thirdCity = City("Hanoi")
firstCity.degrees = first
secondCity.degrees = second
thirdCity.degrees = third
println(first)
println(second)
println(third)
二传手有什么问题?为什么second 没有设置默认值?
【问题讨论】:
-
您传递的
int值是什么 -
我通过了 20,100,35。
-
所以输出应该是
[20, 5, 35],因为只有莫斯科符合条件value > 57 || -92 > value -
您正在打印
first、second和third,它们甚至不是setter 的结果,它们是readLine()s 的结果。所以问题是readLine()s -
另请注意,这里不需要短路运算符
||,您可能应该只使用or。
标签: kotlin