You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin初学者编写计算器代码遇多类报错,请求协助修复

解决Kotlin基础计算器代码错误

原始代码

fun main() {
    print("This is a calculator")
    print("enter your first number")
    val no1 = readLine()!!
    print("enter your operation")
    val operation1 = readLine()!!
    print("enter your second number")
    val no2 = readLine()!!

    val result = if(operation1 == '*')
    print("$val no1 * $val no2")
}

报错信息

'if' must have both main and 'else' branches if used as an expression
Operator '==' cannot be applied to 'String' and 'Char'
Keyword cannot be used as a reference
Keyword cannot be used as a reference


逐个错误修复

1. Keyword cannot be used as a reference

  • 问题原因:字符串模板里错误写了$val,val是Kotlin的关键字,不能作为变量引用放在模板中,直接写变量名即可。
  • 修复方式:把"$val no1 * $val no2"改成"$no1 * $no2"

2. Operator '==' cannot be applied to 'String' and 'Char'

  • 问题原因:readLine()!!返回的是String类型,而'*'是Char类型,Kotlin不允许直接比较不同类型的值。
  • 修复方式:二选一即可:
    • 把比较的操作符改成字符串:operation1 == "*"
    • 把输入的操作符转成Char:operation1.first() == '*'(注意:因使用!!,默认输入不为空,若需兼容空输入需额外处理)

3. 'if' must have both main and 'else' branches if used as an expression

  • 问题原因:你把if当成表达式赋值给了result变量,Kotlin要求表达式式的if必须包含else分支,保证无论什么情况都有返回值。
  • 修复方式:
    • 如果不需要将结果赋值给变量,直接去掉val result =,把if当成语句使用;
    • 如果需要赋值,必须添加else分支处理其他操作符的情况。

额外隐藏问题:字符串无法直接做算术运算

当前代码只是拼接字符串,并没有真正计算数值。需要把输入的字符串转成数字类型(比如Int或Double)才能进行算术运算。


修复后的完整代码

fun main() {
    println("This is a calculator")
    print("Enter your first number: ")
    val no1 = readLine()!!.toDouble()
    print("Enter your operation (+, -, *, /): ")
    val operation1 = readLine()!!
    print("Enter your second number: ")
    val no2 = readLine()!!.toDouble()

    val result = when(operation1) {
        "*" -> no1 * no2
        "+" -> no1 + no2
        "-" -> no1 - no2
        "/" -> if(no2 != 0.0) no1 / no2 else Double.NaN
        else -> Double.NaN
    }

    if(result.isNaN()) {
        println("Invalid operation or division by zero")
    } else {
        println("$no1 $operation1 $no2 = $result")
    }
}

代码说明

  • 用println替代部分print,让提示信息自动换行,交互更友好;
  • 将输入的字符串转为Double类型,支持整数和小数计算;
  • 使用when表达式替代if,更清晰处理多种操作符场景;
  • 增加了除零判断,避免运行时异常;
  • 根据计算结果输出最终值或错误提示。

内容的提问来源于stack exchange,提问作者user17569387

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 07:45:51