Java:输入小数时程序崩溃问题【已解决】
解决IMC计算应用输入小数时崩溃的问题
嘿,我一眼就揪出问题根源啦!从你贴的报错信息来看,你现在是用Integer.parseInt()来解析EditText里的身高/体重输入,但这个方法只能处理纯整数的字符串。当你输入像"1.5"这种带小数点的数值时,它直接就懵圈了,抛出NumberFormatException导致程序崩溃——毕竟计算IMC需要的是小数类型的身高(米)和体重(千克),用整数处理肯定不对呀!
下面给你几个具体的解决步骤:
1. 把整数解析换成浮点数解析
直接把Integer.parseInt()替换成Float.parseFloat()或者Double.parseDouble(),这两个方法能完美识别带小数点的数值。举个例子:
// 原来的错误写法 int height = Integer.parseInt(editTextHeight.getText().toString()); // 修改成Float类型(适合精度要求不高的场景) float height = Float.parseFloat(editTextHeight.getText().toString()); // 或者用Double类型(精度更高,计算IMC更准确) double height = Double.parseDouble(editTextHeight.getText().toString());
2. 加上输入验证(强烈推荐)
为了避免用户输入空内容、字母这类非数字字符也导致崩溃,最好在解析前先做个检查,还能给用户友好提示:
// 先获取输入内容并去掉首尾空格 String heightInput = editTextHeight.getText().toString().trim(); String weightInput = editTextWeight.getText().toString().trim(); // 检查是否为空 if (heightInput.isEmpty() || weightInput.isEmpty()) { Toast.makeText(this, "请填写完整的身高和体重哦", Toast.LENGTH_SHORT).show(); return; } // 用try-catch捕获可能的格式错误 try { double height = Double.parseDouble(heightInput); double weight = Double.parseDouble(weightInput); // 计算IMC公式:体重(kg) ÷ (身高(m) × 身高(m)) double imcValue = weight / (height * height); // 把结果格式化后显示,保留两位小数更直观 textViewResult.setText(String.format("您的IMC值为:%.2f", imcValue)); } catch (NumberFormatException e) { Toast.makeText(this, "请输入正确的数字格式呀", Toast.LENGTH_SHORT).show(); e.printStackTrace(); }
3. 优化EditText的输入类型(可选但实用)
你还可以在布局文件里设置EditText只能输入数字和小数点,从源头减少用户的错误输入:
<EditText android:id="@+id/editTextHeight" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入身高(单位:米)" android:inputType="numberDecimal" /> <EditText android:id="@+id/editTextWeight" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="输入体重(单位:千克)" android:inputType="numberDecimal" />
内容的提问来源于stack exchange,提问作者user9545141
相关产品推荐
相关产品推荐

