我是一名 Android 初学者开发人员,我正在学习一个教程,其中有一个计算用户 BMI 的应用程序。但是,如果用户按下“计算”按钮而不在体重和高度字段中输入任何内容,应用程序就会崩溃。
我想我可以通过检查体重或高度字段是否为空来解决这个问题,如果为真则显示一条消息。但是,Android Studio 告诉我“条件 height == null || Weight == null 始终为 false”,应用程序仍然崩溃。
这是计算按钮的部分代码:
private OnClickListener calculateListener = new OnClickListener() {
@Override
public void onClick(View v) {
String height = height.getText().toString();
String weight = weight.getText().toString();
float hValue = Float.valueOf(h);
if (height == null || weight == null) {
result.setText("Please enter your weight and your height");
} else {
//calculate BMI
float wValue = Float.valueOf(w);
if(group.getCheckedRadioButtonId() == R.id.radio2)
hValue = hValue / 100;
hValue = (float)Math.pow(hValue, 2);
float bmi = wValue / hValue;
result.setText("Your BMI is " + String.valueOf(bmi));
}
}
};
为什么它告诉我条件总是错误的?如果字段中没有任何内容,那么该值不为空吗?
最佳答案
If there's nothing in the fields, is the value not null?
如果字段中没有任何内容,则值将为 ""
,而不是 null
。
所以:
if (height.length() == 0 || weight.length() == 0) {
但是您还需要防止用户输入了某些内容,但无法通过捕获 NumberFormatException
将其转换为 Float
的可能性。 (我也可能会使用 Float.parseFloat
来获得 float
而不是 Float.valueOf
,它会给你一个 Float
。)
另外,除非我犯了很大的错误,否则所示的代码将无法编译。你有:
String height = height.getText().toString();
即使您有 height
实例字段,也会失败
error: variable height might not have been initialized
...和/或
error: cannot find symbol
...因为 height
将解析为本地,它是一个 String
,并且没有 getText()
。要使用实例字段,您需要 YourClassName.this
:
String height = YourClassName.this.height.getText().toString();
...或者更好的是,只需使用不同的局部变量名称。
关于java - 字符串不能为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34870188/