Harley
Harley

Reputation: 1524

Java - if (Float.isNaN(x))

float aa = Float.valueOf(a.getText().toString());
                
if (Float.isNaN(aa)) {
    aa = 0;
}

I'm trying to check for no input from the user and if there's no input just make it zero, sounds simple enough but its not working for me. Its my first android app and it crashes when there is no user input and the user presses the go button. Can anyone help?

Thanks.

Upvotes: 3

Views: 1160

Answers (5)

gaurav5430
gaurav5430

Reputation: 13882

EDIT:

you should check for

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

also Float.valueOf would throw an exception if the value is not a string. you could handle that to set the value to 0, if user has entered a wrong string or no string at all.

Upvotes: 1

Infinite Recursion
Infinite Recursion

Reputation: 6557

Put the first statement inside a try-catch, if an exception does not occur, then input is definitely a valid 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
    }

The possible exceptions which it may throw are:
1. a.getText() -> NullPointerException
2. Float.valueOf -> NumberFormatException

Upvotes: 0

Greg Giacovelli
Greg Giacovelli

Reputation: 10184

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;
}

....

Upvotes: 2

Venkatesh S
Venkatesh S

Reputation: 5494

 // 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; 
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

I'm trying to check for no input from the user and if there's no input just make it zero.

When there's no input or the input is invalid, valueOf does not return a NaN; it throws NumberFormatException. You can add a try/catch around the valueOf call (since you want float, not Float, you should use parseFloat instead to avoid the unnecessary boxing and unboxing of the value):

float aa;

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

Upvotes: 2

Related Questions