gpt4 book ai didi

android - 单击带有空edittext的按钮后,应用程序崩溃

转载 作者:行者123 更新时间:2023-12-03 17:29:22 25 4
gpt4 key购买 nike

我正在使用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";
}
}

最佳答案

您的应用程序崩溃的原因是这些if语句:

if ("".equals(weightText.getText())) {
weight = 1;
}
weightText.getText()不返回 String,而是返回 Editable。另外, Strings具有一种称为 isEmpty()的方法来检查它们是否为空。因此,将ifs替换为以下内容:
if(weightText.getText().toString().isEmpty()) {
...
}

希望我能为您提供帮助,如果您还有其他疑问,请随时提出!

关于android - 单击带有空edittext的按钮后,应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24868470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com