float aa = Float.valueOf(a.getText().toString());
if (Float.isNaN(aa)) {
aa = 0;
}
我正在尝试检查用户是否没有输入,如果没有输入,则将其设置为零,听起来很简单,但对我来说并不起作用。这是我的第一个Android应用程序,当用户没有输入并且用户按下“Go”按钮时,它会崩溃。有人能帮忙吗?
谢谢。
float aa = Float.valueOf(a.getText().toString());
if (Float.isNaN(aa)) {
aa = 0;
}
float aa = 0f;
CharSequence s = a.getText();
if (!TextUtils.isEmpty(s)) {
try {
aa = Float.valueOf(s);
} catch (Exception e) {
// Ok it's not a Float at least
}
}
if (Float.isNaN(aa))
{
aa = 0f;
}
....
valueOf
不会返回 NaN
;它会抛出 NumberFormatException
。您可以在 valueOf
调用周围添加一个 try
/catch
(由于您需要 float
,而不是 Float
,所以应该使用 parseFloat
以避免值的不必要装箱和拆箱):float aa;
try {
aa = Float.parseFloat(a.getText().toString());
} catch (NumberFormatException nfe) {
aa = 0;
}
你应该检查
if( a.getText().toString().equals(""))
另外,如果值不是字符串,Float.valueOf
会抛出异常。如果用户输入了错误的字符串或根本没有输入,则可以处理该异常将值设置为0。
a
是一个 TextView
,则 a.getText()
永远不会返回 null
,a.getText().toString()
也不会返回 null
。 - Ted Hopp // there is some value and check it is nan
if(a.getText().toString()!=null)
{
float aa = Float.valueOf(a.getText().toString());
if (Float.isNaN(aa))
{
aa = 0;
}
}
// there is no value and check it is empty
else if(a.getText().toString() == null || a.getText().toString().equals(""))
{
aa= 0;
}
float aa = 0;
try
{
aa = Float.valueOf(a.getText().toString());
//if above statement executes sucessfully, aa has valid float value here
} catch(Exception e){
//if any exception occurs, input is not a valid float, so value of aa is still 0
//no operation required in catch block
}
a
是什么? - Ted Hopp