在运行我的代码时,我得到一个 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)`
如何防止此异常发生?
最佳答案
"N/A"
不是整数。如果您尝试将其解析为整数,它必须抛出 NumberFormatException
。
解析前检查或正确处理Exception
。
异常处理
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!
...
}
关于java - 如何防止 java.lang.NumberFormatException : For input string: "N/A"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711896/