St.*_*rio 3 java string integer
我想检查是否String
传递给Integer.valueOf(String s)
要解析的有效String.如果一个不可解析,我需要返回0.
我是通过以下方式完成的:
try{
Integer.valueOf(String s)
} catch(NumberFormatException e) {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这样做是不好的方法吗?
方法1:使用正则表达式检查作为数字的有效性
public static int parseStrToInt(String str) {
if (str.matches("\\d+")) {
return Integer.parseInt(str);
} else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
方法2:使用Java的内置java.text.NumberFormat对象来查看解析字符串后解析器位置是否在字符串的末尾.如果是,我们可以假设整个字符串是数字
public static int strToInt(String str) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
if (str.length() == pos.getIndex()) {
return Integer.parseInt(str);
} else {
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
我会用:
s = s.trim(); // sometimes user inputs white spaces without knowing it
int value;
if (s.length() == 0) {
value = 0; // obviously not a string
} else {
try{
value = Integer.valueOf(s);
} catch(NumberFormatException e) {
value = 0;
}
}
// do whatever you like here
Run Code Online (Sandbox Code Playgroud)