我在将字符串解析为整数时遇到了一些问题,我不知道问题是什么。
我正在将一个带有整数值的字符串传递给我的函数,以检查它是否可以解析。
这是我的职能。
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 之前尝试修剪它,也许这会有所帮助。