如何防止 java.lang.NumberFormatException: For input string: "N/A"?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18711896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I prevent java.lang.NumberFormatException: For input string: "N/A"?
提问by codemaniac143
While running my code I am getting a 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)`
How can I prevent this exception from occurring?
如何防止发生此异常?
采纳答案by Subhrajyoti Majumder
"N/A"
is not an integer. It must throw NumberFormatException
if you try to parse it to an integer.
"N/A"
不是整数。NumberFormatException
如果您尝试将其解析为整数,则它必须抛出。
Check before parsing or handle Exception
properly.
解析前检查或Exception
正确处理。
Exception Handling
try{ int i = Integer.parseInt(input); } catch(NumberFormatException ex){ // handle your exception ... }
异常处理
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!
...
}
回答by rocketboy
"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:
"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;
}
回答by Ruchira Gayan Ranaweera
Obviously you can't parse N/A
to int
value. you can do something like following to handle that NumberFormatException
.
显然,您无法解析N/A
为int
值。您可以执行以下操作来处理该问题NumberFormatException
。
String str="N/A";
try {
int val=Integer.parseInt(str);
}catch (NumberFormatException e){
System.out.println("not a number");
}
回答by Jayamohan
Integer.parseInt(str)throws NumberFormatException
if the string does not contain a parsable integer. You can hadle the same as below.
NumberFormatException
如果字符串不包含可解析的整数,则Integer.parseInt(str)抛出。你可以像下面一样处理。
int a;
String str = "N/A";
try {
a = Integer.parseInt(str);
} catch (NumberFormatException nfe) {
// Handle the condition when str is not a number.
}
回答by Rajaprabhu Aravindasamy
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