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

Android开发报错:Amount函数空字符串问题排查求助

Android开发空字符串错误排查与解决

你遇到的空字符串错误根源很明确:在Activity刚初始化时就获取了EditText的文本,这时候用户还没输入任何内容,message是空字符串。后续点击按钮调用Amount函数时,传入的依然是这个初始化时的空值,而非用户输入的内容,所以触发了字符串转数字的错误。

代码问题分析

  • 在onCreate方法里,你直接执行val message: String = editText.text.toString(),此时界面刚加载完成,EditText没有用户输入,message必然是空字符串。
  • 你把这个空的message传给了getSignal方法,点击按钮时调用Amount函数用的还是这个旧值,根本没去获取用户后来输入的内容。

修复方案

修改代码逻辑,在点击按钮时实时获取EditText的最新文本,同时增加输入校验避免崩溃:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val editText: EditText = findViewById(R.id.cost_of_service)
    val radioGroup: RadioGroup = findViewById(R.id.tip_options)
    val cal: Button = findViewById(R.id.calculate_button)
    val tv: TextView = findViewById(R.id.tip_result)

    getSignal(radioGroup, cal, editText, tv)
}

private fun getSignal(radioGroup: RadioGroup, cal: Button, editText: EditText, tv: TextView){
    cal.setOnClickListener{
        val selectedRB: RadioButton = findViewById(radioGroup!!.checkedRadioButtonId)
        val per: String = selectedRB.text.toString()
        // 点击按钮时才获取用户输入的内容
        val message: String = editText.text.toString()
        
        // 先校验输入合法性
        if (message.isBlank()) {
            tv.text = "请输入服务金额"
            return@setOnClickListener
        }
        try {
            val amount: Double = Amount(per, message)
            // 格式化结果为两位小数,更符合金额显示习惯
            tv.text = String.format("%.2f", amount)
        } catch (e: NumberFormatException) {
            tv.text = "请输入有效数字"
        }
    }
}

private fun Amount(per: String, message: String): Double {
    val baseAmount = message.toDouble()
    val tipPercent = per.toInt()
    // 统一用Double计算,避免int转换丢失小数精度
    return baseAmount + (baseAmount * tipPercent) / 100.0
}

额外优化说明

  1. 输入校验:增加空值和非法数字判断,避免程序崩溃
  2. 精度优化:计算小费不再混用toInt()和toDouble(),防止小数金额的精度丢失
  3. 结果格式化:用String.format保留两位小数,显示更专业

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:55:17