如何防止java.lang.NumberFormatException:对于输入字符串:“N / A”?

时间:2013-09-10 06:17:58

标签: java string int numberformatexception

在运行我的代码时,我收到了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)`

如何防止发生此异常?

5 个答案:

答案 0 :(得分:74)

"N/A"不是整数。如果您尝试将其解析为整数,则必须抛出NumberFormatException

解析前检查。或正确处理Exception

  1. 异常处理*
  2. try{
       int i = Integer.parseInt(input);
    }catch(NumberFormatException ex){ // handle your exception
       ...
    }
    

    或 - 整数模式匹配 -

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

答案 1 :(得分:5)

显然,您无法将N/A解析为int值。你可以做以下事情来处理NumberFormatException

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 

答案 2 :(得分:5)

制作一个像这样的异常处理程序,

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

.
.
.
.

int xTest = ConvertIntoNumeric("N/A");  //Will return 0

答案 3 :(得分:4)

如果字符串不包含可解析的整数,则

Integer.parseInt(str)抛出NumberFormatException。你可以像下面一样。

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

try {   
   a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
  // Handle the condition when str is not a number.
}

答案 4 :(得分:2)

“N / A”是一个字符串,无法转换为数字。抓住异常并处理它。例如:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }