如何避免java.lang.NumberFormatException: For input string: "N/A"错误?

100
在运行我的代码时出现了一个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)`

我该如何防止出现这个异常?


6个回答

117

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

在解析之前进行检查或正确处理 Exception

  1. 异常处理

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
是的,你说得对,我忘记将它分配给整数值了。 现在我收到了错误提示,但是问题已经成功解决了。 谢谢。 - codemaniac143
+1 是整数模式匹配。我不确定如何使用 try/catch 循环从 stdin 读取一行。 - Jason Hartley
@JasonHartley,请查看答案。我已经编辑并解释了为什么您不希望在代码中使用整数模式匹配。 - LPVOID
如何从双引号中的字符串“151564”中获取整数? - Zeeshan Ali

10
如果字符串不包含可解析的整数,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.
}

9

按照以下方式创建异常处理程序:

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

.
.
.
.

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

7
显然,你不能将“N/A”解析为“int”值。你可以采取以下方法处理“NumberFormatException”。
   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 

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

2

'N/A' 无法解析为整数,我们会收到异常,并且提供的字符串可能是 <-2147483648 或 > 2147483648(int 的最大值和最小值),在这种情况下,我们也会收到数字格式异常。在这种情况下,我们可以尝试以下操作。

String str= "8765432198";
Long num= Long.valueOf(str);
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
Integer n=0;
if (num > max) {
        n = max;
    }
if (num < min) {
        n = min;
    }
if (num <= max && num >= min)
  n = Integer.valueOf(str);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接