有人可以解释可以解决Kotlin中的这个问题吗?非常感谢
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"
答案 0 :(得分:1)
您收到该错误,因为使用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
}