float aa = Float.valueOf(a.getText().toString());
if (Float.isNaN(aa)) {
aa = 0;
}
我正在尝试检查用户是否没有输入,如果没有输入就将其设为零,这听起来很简单,但对我来说不起作用。这是我的第一个 android 应用程序,当没有用户输入并且用户按下 go 按钮时它崩溃了。谁能帮忙?
谢谢。
最佳答案
I'm trying to check for no input from the user and if there's no input just make it zero.
当没有输入或输入无效时,valueOf
不返回NaN
; it throws NumberFormatException
.您可以在 valueOf
调用周围添加一个 try
/catch
(因为您需要 float
,而不是 Float
,您应该使用 parseFloat
来避免对值进行不必要的装箱和拆箱):
float aa;
try {
aa = Float.parseFloat(a.getText().toString());
} catch (NumberFormatException nfe) {
aa = 0;
}
关于Java - 如果 (Float.isNaN(x)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20696542/