In Java operations, it often involves converting string strings to int numbers.
which strings can be converted to numbers, which cannot, and cannot always be judged by whether Integer.parseint () throws an exception.
Just met the conversion situation, summed up the next, share it out.
Defining Method signatures
/**
* To see if a string can be converted to a number
* @param str string
* @return true; false can not */public
Static Boolean Isstr2nu M (String str) {
}
How do you implement the method body? Two different ways
Method 1 Integer.parseint Conversion
try {
integer.parseint (str);
return true;
} catch (NumberFormatException e) {return
false;
}
Method 2 Regular Expression
Pattern pattern = pattern.compile ("^[0-9]*$");
Matcher Matcher = Pattern.matcher (str);
return matcher.matches ();
Integer also has a static method valueof (String s) to view the source
public static Integer valueof (String s) throws NumberFormatException {return
integer.valueof (parseint (s));
valueof (string s) also first converts the string to a number by parseint () before converting it to an integer object.
and parseint (String s) returns an int variable, saving the overhead of heap memory
public static int parseint (String s) throws NumberFormatException {return
parseint (s,10);
}
So, here's the judgment to use parseint on it.