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

Kotlin单位转换App报错‘表达式未使用’且计算结果异常求助

Kotlin单位转换App问题修复:未使用表达式警告与计算结果异常

一、解决"The Expression is unused"警告

问题原因

  • 在calculateButton()的else块中,你定义并调用了calculateHeight变量,但仅写出变量却未对其做任何实际操作(比如赋值、传参),Kotlin会识别为未使用表达式并抛出警告。
  • 原输入校验逻辑存在漏洞:两个独立的if判断会导致,比如英尺为空时弹出提示,但只要英寸不为空,程序仍会执行displayText(),不符合"必填项未填则不计算"的预期。

修复方案

  1. 移除无用的变量引用,直接在需要时调用计算函数或复用计算结果。
  2. 合并输入校验逻辑,先确认所有必填项填写完整,通过后再执行计算和显示。

二、解决计算结果始终为30.48厘米的异常

问题原因

  1. 输入获取错误:binding.editTextFeet.toString()拿到的是EditText组件的描述字符串(如android.widget.EditText@xxxx),而非用户输入的文本,正确写法应为binding.editTextFeet.text.toString(),英寸同理。
  2. 计算逻辑错误:totalInches = inches + 1f完全错误,正确逻辑是将英尺转换为英寸(1英尺=12英寸),再加上输入的英寸数,总英寸数乘以2.54得到厘米数。
  3. 默认值不合理:feet默认设为1,会导致未输入英尺时程序默认按1英尺计算,应改为0。
  4. 重复计算:displayText()每次重新调用calculateHeight(),没必要重复执行计算,可将结果作为参数传入。

修复后完整代码

calculateButton() 修复版

private fun calculateButton() {
    val feetString = binding.editTextFeet.text.toString()
    val inchesString = binding.editTextInches.text.toString()

    // 统一校验输入,有一项为空就提示并终止逻辑
    when {
        feetString.isEmpty() && inchesString.isEmpty() -> 
            Toast.makeText(context, "请输入英尺和英寸数值", Toast.LENGTH_SHORT).show()
        feetString.isEmpty() -> 
            Toast.makeText(context, "请输入英尺数值", Toast.LENGTH_SHORT).show()
        inchesString.isEmpty() -> 
            Toast.makeText(context, "请输入英寸数值", Toast.LENGTH_SHORT).show()
        else -> {
            // 校验通过,计算并显示结果
            val heightInCm = calculateHeight()
            displayText(heightInCm)
        }
    }
}

calculateHeight() 修复版

private fun calculateHeight(): Double {
    val feetString = binding.editTextFeet.text.toString()
    val inchesString = binding.editTextInches.text.toString()

    var feet = 0
    try {
        feet = feetString.toInt()
    } catch (e: NumberFormatException) {
        e.printStackTrace()
    }

    var inches = 0f
    try {
        inches = inchesString.toInt().toFloat()
    } catch (e: NumberFormatException) {
        e.printStackTrace()
    }

    // 正确的单位转换逻辑:总英寸数 = 英尺*12 + 输入英寸,再转厘米
    val totalInches = (feet * 12) + inches
    return totalInches * 2.54
}

displayText() 修复版

private fun displayText(heightInCm: Double) {
    val dec = DecimalFormat(".##")
    val resultString = dec.format(heightInCm)
    binding.textViewCm.text = "$resultString - 厘米"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:05:18