method 1: use a regular expression to check for validity of being a number
public static int parseStrToInt(String str) {
if (str.matches("\\d+")) {
return Integer.parseInt(str);
} else {
return 0;
}
}
method 2: use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric
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;
}
}