Java Conversion
Java Conversion
To convert a string value to a number (for example, to convert the String value in a text field to an
int), use these methods. Assume the following declarations:
int i = Integer.parseInt(s);
long l = Long.parseLong(s);
float f = Float.parseFloat(s);
double d = Double.parseDouble(s);
If s is null or not a valid representation of a number of that type, these methods will throw
(generate) a NumberFormatException.
Handling NumberFormatExceptions
Put number conversions inside a try . . . catch statement so that you can do something if
bad input is entered. The conversion method will throw a NumberFormatException when there is
bad input. Catch the NumberFormatException, and do something to handle this error condition.
Put your conversion in the try clause, and the error handling in the catch clause. Here is an
example of the kind of utility function you might write to do this checking.