How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

codemaniac143 picture codemaniac143 · Sep 10, 2013 · Viewed 716.4k times · Source

While running my code I am getting a NumberFormatException:

java.lang.NumberFormatException: For input string: "N/A"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.valueOf(Unknown Source)
    at java.util.TreeMap.compare(Unknown Source)
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)`

How can I prevent this exception from occurring?

Answer

Subhrajyoti Majumder picture Subhrajyoti Majumder · Sep 10, 2013

"N/A" is not an integer. It must throw NumberFormatException if you try to parse it to an integer.

Check before parsing or handle Exception properly.

  1. Exception Handling

    try{
        int i = Integer.parseInt(input);
    } catch(NumberFormatException ex){ // handle your exception
        ...
    }
    

or - Integer pattern matching -

String input=...;
String pattern ="-?\\d+";
if(input.matches("-?\\d+")){ // any positive or negetive integer or not!
 ...
}