There are two common methods of string to int in Java:
The first method: I=integer.parseint (str);
The second method: I=integer.valueof (str). Intvalue ();
Both of these methods can implement string to int, but there is a difference between the two, the first method directly uses the string type of static method, the second method will produce more than one object. But both will throw an exception.
Here's a look at using parseint (str), when STR is not a number, throw an exception solution:
First, wrap the parseint () with a try catch, accept the exception information yourself, and implement the solution.
e.g.
try{
Integer i = integer.parseint (str);
}
catch (Exception e)
{
SYSTEM.OUT.PRINTLN ("Transition Failure")
}
Second, use regular expressions to filter
e.g.
}
The Third Kind: write the function, judge the string, call the Jave's own judgment whether it is a function of the number, also can increase the readability
e.g.
for (int i = 0; i < str.length (); i++) {
if (!character.isdigit (Str.charat (i))) {
return false;
}
}
Finally, sometimes reading a string is necessary to remove the front and back space, or throw an exception, this time we use the String.Trim ("") function can be used to remove the first end of the string blank.
Software Test week fourth--string to int