Variables Kotlin变量用法“;变量必须为“初始化”;
有人能解释一下在科特林能解决这个问题吗?多谢各位Variables Kotlin变量用法“;变量必须为“初始化”;,variables,kotlin,initialization,Variables,Kotlin,Initialization,有人能解释一下在科特林能解决这个问题吗?多谢各位 var weight = rweight.text.toString().toFloat() var hct = rhct.text.toString().toFloat() var EBV :Float var ABL :Float if (rman.isChecked){ EBV = weight * 75 } else if (rwoman.isChecked) { EBV = weight * 65 } ABL = EB
var weight = rweight.text.toString().toFloat()
var hct = rhct.text.toString().toFloat()
var EBV :Float
var ABL :Float
if (rman.isChecked){
EBV = weight * 75
} else if (rwoman.isChecked) {
EBV = weight * 65
}
ABL = EBV * (10)/hct //error in here "EBV must be initialize"
您收到该错误是因为
EBV
在使用时可能未初始化
您应该使用默认值初始化EBV
变量:
var EBV: Float = 0.0f // or some other default value
或在条件中添加else
子句:
EBV = if (rman.isChecked) {
weight * 75
} else if (rwoman.isChecked) {
weight * 65
} else {
0.0f // assign some value to the variable
}
// As improvement you can replace `if` with `when` statement:
EBV = when {
rman.isChecked -> weight * 75
rwoman.isChecked -> weight * 65
else -> 0.0f // assign some value to the variable
}
尝试将其初始化为类似于
var EBV:Float=0.0
?我认为你的if和else if都不是真的,所以EBV在那一行是空的。@PhaniRithvij是的,非常感谢你的回答。问题在我的代码中。非常感谢。使用“when”的第二种方法是为我工作。