How can I prevent java.lang.NumberFormatException:

2018-12-31 22:33发布

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?

5条回答
余生无你
2楼-- · 2018-12-31 23:05

Obviously you can't parse N/A to int value. you can do something like following to handle that NumberFormatException .

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 
查看更多
深知你不懂我心
3楼-- · 2018-12-31 23:05

Integer.parseInt(str) throws NumberFormatException if the string does not contain a parsable integer. You can hadle the same as below.

int a;
String str = "N/A";

try {   
   a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
  // Handle the condition when str is not a number.
}
查看更多
无色无味的生活
4楼-- · 2018-12-31 23:17

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }
查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 23:23

"N/A" is not integer. It must throw NumberFormatException if you try to parse it to 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!
 ...
}
查看更多
人间绝色
6楼-- · 2018-12-31 23:24

Make an exception handler like this,

private int ConvertIntoNumeric(String xVal)
{
 try
  { 
     return Integer.parseInt(xVal);
  }
 catch(Exception ex) 
  {
     return 0; 
  }
}

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0
查看更多
登录 后发表回答