在运行我的代码时,我收到了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)`
如何防止发生此异常?
答案 0 :(得分:74)
"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!
...
}
答案 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;
}