【发布时间】:2016-05-14 04:41:35
【问题描述】:
当我输入数字时按钮工作正常,但当我不输入时它会崩溃。为了解决这个问题,我尝试使用条件语句,这样如果没有输入数字,计算按钮就不会运行,但它仍然不起作用。我放了一个 else 行看看它是否打印任何东西,但仍然没有。
public void onClick(View view) {
//This is where I tried to fix it
if (percentageText.getText()!=null && numberText.getText()!=null){
float percentage = Float.parseFloat(percentageText.getText().toString());
float dec = percentage / 100;
float total = dec * Float.parseFloat(numberText.getText().toString());
totalTextView.setText(Float.toString(total));
Log.d("myTag","Success!");
} else {
Log.d("myTag","Error no integer found");
}
}
这是日志: error
但是如果我解析 float 并不重要,因为 if 语句会阻止代码运行,对吧?还是它会尝试运行?
【问题讨论】:
-
你试过用
try-catch包围它吗? -
你能在这里发布 logcat 错误吗?
-
您正在解析为
float这可能是问题所在。显示您的 logcat 以获取更多信息。 -
尝试添加另一个条件检查以及空条件检查。 (numberText.getText().toString().trim().getlength > 0 ) 或 (!numberText.getText().toString().trim().equalignourcase("")) 将此应用于百分比编辑文本和数字文本编辑文本
-
@v-v 您的解决方案有效,谢谢!