In Java operations, the case of converting string strings to int numbers is often involved.
which strings can be converted to numbers, which are not, and can not always be judged by whether Integer.parseint () throws an exception.
Just met the conversion situation, summed up the next, share out.
Defining Method signatures
/*** See if a string can be converted to a number * @param str string * @return true Yes; False can not */public static Boolean isstr2num (String str) {}
How should the method body be implemented? 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 code
public static Integer ValueOf (String s) throws NumberFormatException { return integer.valueof (parseint (S, 10));}
ValueOf (string s) also first converts a string to a number by parseint () before converting it to an integer object.
parseint (String s) returns a variable of type int, saving the overhead of heap memory
public static int parseint (String s) throws NumberFormatException { return parseint (s,10);}
So, the judgment here is to use parseint.
Java determines whether a string can be converted to a number