简体   繁体   English

输入字符串 Edittext 的 NumberFormatException

[英]NumberFormatException for input string Edittext

var bmi: Float
if(binding.rbMetric.isChecked){
    bmi = binding.currWeightEdit.text.toString().toFloat() / binding.meterEditText.toString().toFloat().pow(2)
}else{
    bmi = (binding.currWeightEdit.text.toString().toFloat()*703)/ (binding.feetEditText.text.toString().toInt()*12 + binding.inchesEditText.toString().toInt()).toFloat().pow(2)
}
return bmi

This code is meant to calculate the BMI for either the metric or imperial unit.此代码用于计算公制或英制单位的 BMI。 The input type of the Editexts weight and meter are numberDecimal and meter,feet are number. Editexts weight 和 meter 的输入类型是 numberDecimal,meter,feet 是 number。 The error is: java.lang.NumberFormatException: For input string: "com.google.android.material.textfield.TextInputEditText{b7d8c80 VFED..CL. ........ 0,0-385,153 #7f0800cc app:id/inches_edit_text aid=1073741832}".错误是:java.lang.NumberFormatException:对于输入字符串:“com.google.android.material.textfield.TextInputEditText{b7d8c80 VFED..CL......... 0,0-385,153 #7f0800cc 应用程序: id/inches_edit_text 辅助 = 1073741832}”。 How can I fix this?我怎样才能解决这个问题?

On the first calculation you used在您使用的第一次计算中

binding.meterEditText.toString().toFloat().pow(2)

when it should have been应该是什么时候

binding.meterEditText.text.toString().toFloat().pow(2)

So it was calling toString() on the EditText view itself.所以它在 EditText 视图本身上调用toString() You repeated this error further down where you used toInt() .您在使用toInt()地方进一步重复了此错误。

To make this code less repetitive and error prone, you could use an extension.为了减少此代码的重复性和错误率,您可以使用扩展名。 Also, when using binding over and over, it's cleaner to use with(binding) .此外,当一遍又一遍地使用binding时,使用with(binding)更干净。

val TextView.textAsFloat: Float get() = text.toString().toFloat()

return with(binding) {
    if (rbMetric.isChecked) {
        currWeightEdit.textAsFloat / meterEditText.textAsFloat.pow(2)
    } else {
        currWeightEdit.textAsFloat * 703 / (feetEditText.textAsFloat * 12 + inchesEditText.textAsFloat).pow(2)
    }
}

Update your code on, you are getting editText input in wrong way.更新您的代码,您以错误的方式获得 editText 输入。

var bmi: Float
    if(binding.rbMetric.isChecked){
        //replace below line in your actual code
        binding.meterEditText.text.toString().toFloat().pow(2)
        bmi = binding.currWeightEdit.text.toString().toFloat() / binding.meterEditText.toString().toFloat().pow(2)
    }else{
        //replace below line in your actual code
         binding.inchesEditText.text.toString().toInt()).toFloat().pow(2)
        bmi = (binding.currWeightEdit.text.toString().toFloat()*703)/ (binding.feetEditText.text.toString().toInt()*12 + binding.inchesEditText.toString().toInt()).toFloat().pow(2)
    }
    return bmi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM