Adham
Adham

Reputation: 64904

parsing empty string to integer in java

if(jsonArray.getJSONObject(i).get("SECNO").toString()!=null && jsonArray.getJSONObject(i).get("SECNO").toString().trim()!="")
                        appointment.mSecNo =Integer.parseInt(jsonArray.getJSONObject(i).get("SECNO").toString());
                    else
                        appointment.mSecNo = -1;

In the previouse lines, when the value of jsonArray.getJSONObject(i).get("SECNO").toString() equales to '' it doesn't be caught by the if statement ..

and I get this error message .. can't parse '' to integer

Upvotes: 1

Views: 17533

Answers (3)

Dunes
Dunes

Reputation: 40763

Don't compare Strings with ==

See: Java comparison with == of two strings is false? , Java String.equals versus ==

Upvotes: 0

Rosdi Kasim
Rosdi Kasim

Reputation: 26016

Why not just,

int appointment.mSecNo = -1;

try {
    appointment.mSecNo = Integer.parseInt(jsonArray.getJSONObject(i).get("SECNO").toString());
}catch(Exception e) {
    log.error(" your error message ");
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502256

Don't use == or != to compare strings in Java - it only compares the references, not the contents of the strings. Also, I doubt that toString would ever return null. I suspect you want:

Foo x = jsonArray.getJSONObject(i).get("SECNO");
if (x != null && x.toString().trim().length() > 0)

(I don't know what the type of jsonArray.getJSONObject(i).get("SECNO") would be, hence the Foo.)

In this particular case I've used length() > 0 to detect a non-empty string - but for more general equality, you'd want to use equals, so an alternative is:

if (x != null && !x.toString().trim().equals(""))

Upvotes: 2

Related Questions