我在将字符串解析为整数时遇到一些问题,我不知道问题是什么。
我正在将具有整数值的字符串传递给函数,以检查其是否可解析。
这是我的职责。
private boolean isNumeric (String value){
try {
System.out.println("VALUE = " +value);
int x = Integer.parseInt(value);
return true;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
return false;
}
}
我通过打印到控制台进行检查。这是结果。
I/System.out: VALUE = 77
NumberFormatException: Invalid int: "77"
你们能帮我弄清楚这里出什么问题了吗?原因我无法将此字符串转换为整数。
您可以尝试执行此操作,因为这会删除输入中的所有空格:
private boolean isNumeric (String value){
try {
System.out.println("VALUE = " +value);
int x = Integer.parseInt(value.trim());
return true;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
return false;
}
}
如果字符串不可解析,则parseInt()
应返回NumberFormatException,但应为“ 77”。因此,在将其解析为int之前,应尝试对其进行修剪,这可能会有所帮助。