尝试捕获null或0输入。如果进行了空输入,应用程序崩溃,如果输入0,它会通过错误并返回奇怪的数学!
case_cost = (EditText) findViewById(R.id.case_cost);
dilution = (EditText) findViewById(R.id.dilution);
answer =(TextView) findViewById(R.id.answer);
ounces_pc = (TextView) findViewById(R.id.ounces_pc);
Button finishBtn = (Button) findViewById(R.id.button3);
finishBtn.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Method
if (((Float.valueOf(dilution.getText().toString())) == 0) ||
(dilution.getText().equals(null))) {
String errMsg = "Missing Dilution";
answer.setText(errMsg);
} else;
调试信息:
StringToReal.invalidReal(String, boolean) line: 63
StringToReal.parseFloat(String) line: 289
Float.parseFloat(String) line: 300
Float.valueOf(String) line: 337
UccActivity$1.onClick(View) line: 47
Button(View).performClick() line: 4102
View$PerformClick.run() line: 17063
Handler.handleCallback(Message) line: 615
ViewRootImpl$ViewRootHandler(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 155
ActivityThread.main(String[]) line: 5454
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not
available [native method]
Method.invoke(Object, Object...) line: 511
ZygoteInit$MethodAndArgsCaller.run() line: 1029
ZygoteInit.main(String[]) line: 796
NativeStart.main(String[]) line: not available [native method]
Thread [<10> Binder_2] (Running)
Thread [<9> Binder_1] (Running)"
答案 0 :(得分:0)
在检查值之前,您应该检查Null。否则,当它检查0并且值为Null时,它将抛出异常。
答案 1 :(得分:0)
这种方法允许你输入无效的字符串(字母)而不是崩溃(你的将按原样)。此外,您的0检查不起作用,因为您正在将int与浮点数进行比较..您应该使用0f
String text = dilution.getText().toString();
if (TextUtils.isEmpty(text)) {
answer.setText("Empty input");
return;
}
try {
Float value = Float.valueOf(text);
if (value == null || value == 0f) {
answer.setText("Zero");
}
} catch (NumberFormatException e) {
answer.setText("Invalid input");
}