gpt4 book ai didi

Kotlin:必须初始化变量 'result'

转载 作者:IT老高 更新时间:2023-10-28 13:44:14 25 4
gpt4 key购买 nike

编译器显示错误 Kotlin: Variable result must be initialized.

这里是代码。

fun main(args: Array<String>) {
print("Enter two numbers: ")

// nextDouble() reads the next double from the keyboard
var first= readLine()!!.toDouble()
var second = readLine()!!.toInt()

print("Enter an choice(1-4)): ")
val operator = readLine()!!.toInt()

var result: Double

when (operator) {
1 -> result = first + second
2 -> result = first - second
3 -> result = first * second
4 -> result = first / second

else -> {
println("Error.")
}
}

println("The result is :- " +result)
}

最佳答案

问题是当你在这里读取 result 的值时:

println("The result is :- " +result)

result 可能没有初始化,因为这里:

var result: Double

when (operator) {
1 -> result = first + second
2 -> result = first - second
3 -> result = first * second
4 -> result = first / second

else -> {
println("Error.")
}

您没有为 else 分支中的 result 赋值。您有多种选择,一种可能是使 result 可以为空。例如:

var result = when (operator) {
1 -> first + second
2 -> first - second
3 -> first * second
4 -> first / second
else -> null
}

if (result != null) {
println("The result is :- " + result)
} else {
println("Error.")
}

请注意,如果运算符不是 (1-4),则 result 的值将为 null。此外,在您的代码中,您正在打印“错误”,然后您再次尝试打印结果。

要添加更多内容,如果您使用 when 语句作为方法引用来定义运算符,则可以使事情变得更好:

print("Enter an choice(1-4)): ")
val operatorCode = readLine()!!.toInt()

val operator: ((Int) -> Double)? = when (operatorCode) {
1 -> first::plus
2 -> first::minus
3 -> first::times
4 -> first::div
else -> null
}

if (operator != null) {
val result = operator.invoke(second)
println("The result is :- " + result)
} else {
println("Error.")
}

关于Kotlin:必须初始化变量 'result',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49199281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com