我有一个包含数字的字符串。
我有下面这段代码:
String tempStr = "+123";
NumberFormat numformat = NumberFormat.getNumberInstance();
numformat.setParseIntegerOnly(true);
try {
int ageInDays = Integer.parseInt(tempStr);
System.out.println("the age in days "+ageInDays);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
对于带有负号的数字,它可以正常工作。但是,我无法处理带有“+”符号的数字。它会抛出NumberFormatException。
那么,我该如何从字符串中解析带有“+”符号的数字呢?
Integer.parseInt("+123")
。我也测试了你的代码,并且在使用Java 8时也有效。如果需要更多细节信息,请查看这个问题和答案。 - MadProgrammer