【发布时间】:2014-07-21 23:31:01
【问题描述】:
我正在开发 BMI 计算器应用程序。它有两个editText、一个按钮和三个textView。如果单击该按钮,您将获得 BMI,但当一个或两个 edittext 字段为空时,应用程序会崩溃。我在我的代码中看不到任何错误。你能帮我一个人吗? 非常感谢
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.calculateButton) {
EditText weightText = (EditText)findViewById(R.id.weightText);
EditText heightText = (EditText)findViewById(R.id.heightText);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
float weight;
if ("".equals(weightText.getText())) {
weight = 1;
} else {
weight = Float.parseFloat(weightText.getText().toString());
}
float height;
if ("".equals(heightText.getText())) {
height = 1;
} else {
height = Float.parseFloat(heightText.getText().toString());
}
float bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
resultText.setText(bmiValue + "-" + bmiInterpretation);
}
}
private float calculateBMI (float weight, float height) {
return (float) (weight / ((height / 100) * (height / 100)));
}
private String interpretBMI(float bmiValue) {
if (bmiValue < 16) {
return "Severely underweight";
} else if (bmiValue >=16 && bmiValue < 18.5) {
return "Underweight";
} else if (bmiValue >= 18.5 && bmiValue < 25) {
return "Normal";
} else if (bmiValue >= 25 && bmiValue < 30) {
return "Overweight";
} else if (bmiValue >= 30) {
return "Obese";
} else {
return "Incorrect BMI";
}
}
【问题讨论】:
-
总是如果您遇到异常,请在您的问题中包含 logcat。
-
您的
if语句应该使用toString()方法...if ("".equals(weightText.getText().toString()))但try/catch会更好(更简单?)。是的,正如 Xaver 所说的那样。 -
我在你的代码中看不到按钮...
-
@AlexBalo 可能在 xml 中设置
public void calculateClickHandler(View view) -
一些改进:这是错误的
"".equals(heightText.getText())而不是这样做heightText.getText().toString().isEmpty()。这个转换为float是多余的:return (float) (weight / ((height / 100) * (height / 100)));,你不需要在这里只使用float。并且您应该全局保存EditTexts的实例。
标签: android crash android-edittext