在编译后我要做的是,在readLine中写一些东西,我按enter(return),所以这应该使bevarage等于null,所以我应该看到“ variable drink equal null”和“ Buttered Ale”,但是我看到的是没有(空行),似乎饮料不等于null,为什么?以及如何解决使饮料等于零的问题?
fun main() {
var beverage:String? = readLine()
if(beverage !=null){
beverage =beverage .capitalize()
}else{
println("variable beverage equal null")
}
val beverageServed: String = beverage ?: "Buttered Ale"
println(beverageServed)
}
答案 0 :(得分:0)
很高兴您认识Elvis运算符,但是这次,要修复该错误,我建议使用经典的if / else进行更有效的测试,以涵盖不输入任何内容的情况
因此替换此行:val beverageServed: String = beverage ?: "Buttered Ale"
通过这个:
val beverageServed: String = if ((beverage != null) && (beverage != "")) beverage else "Buttered Ale"
答案 1 :(得分:0)
使用isNullOrBlank
或isNullOrEmpty
代替检查空相等性:
var beverage: String? = readLine()
if (beverage.isNullOrEmpty()) {
beverage = beverage.capitalize()
}
为简洁起见,您还可以使用更多可为空的链接:
println(
beverage
?.ifBlank { null }
?.capitalize()
?: "Buttered Ale"
)