【问题标题】:Java - if (Float.isNaN(x))Java - if (Float.isNaN(x))
【发布时间】:2014-01-08 21:32:52
【问题描述】:
float aa = Float.valueOf(a.getText().toString());
                
if (Float.isNaN(aa)) {
    aa = 0;
}

我正在尝试检查用户是否没有输入,如果没有输入,则将其设为零,这听起来很简单,但对我不起作用。它是我的第一个 android 应用程序,当没有用户输入并且用户按下 go 按钮时它会崩溃。有人可以帮忙吗?

谢谢。

【问题讨论】:

  • 也检查 null :) 因为原始值是一个字符串,
  • 请在应用程序崩溃时发布 logcat 输出,以及基于堆栈跟踪的相关代码。如果用户提供输入,它会崩溃吗? a 是什么?

标签: java android if-statement nan


【解决方案1】:
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;
}

....

【讨论】:

    【解决方案2】:

    我正在尝试检查用户是否没有输入,如果没有输入,则将其设为零。

    当没有输入或输入无效时,valueOf 不返回NaNit throws NumberFormatException。您可以在valueOf 调用周围添加try/catch(因为您想要float,而不是Float,您应该使用parseFloat 来避免不必要的值的装箱和拆箱):

    float aa;
    
    try {
        aa = Float.parseFloat(a.getText().toString());
    } catch (NumberFormatException nfe) {
        aa = 0;
    }
    

    【讨论】:

      【解决方案3】:

      编辑:

      你应该检查

       if( a.getText().toString().equals(""))
      

      如果值不是字符串,Float.valueOf 也会抛出异常。如果用户输入了错误的字符串或根本没有字符串,您可以将其设置为 0。

      【讨论】:

      • 假设aTextViewa.getText() 永远不会返回nulla.getText().toString() 也不会。
      【解决方案4】:
       // 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; 
          }
      

      【讨论】:

        【解决方案5】:

        把第一条语句放在一个try-catch里面,如果没有发生异常,那么input肯定是一个有效的float。

            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
            }
        

        它可能抛出的异常是:
        1.a.getText() -> NullPointerException
        2. Float.valueOf -> NumberFormatException

        【讨论】:

          猜你喜欢
          • 2013-12-23
          • 1970-01-01
          • 2020-02-28
          • 1970-01-01
          • 2020-12-07
          • 2021-07-11
          • 1970-01-01
          相关资源
          最近更新 更多