Checking Whether a String Is a Valid Number


try {     int result = Integer.parseInt(aString); } catch (NumberFormatException ex) {    System.out.println(       "The string does not contain a valid       number."); }



In this phrase, we use the parseInt() static method of the Integer class to attempt to convert the string parameter into an integer. If the string parameter cannot be converted into a valid integer, the NumberFormatException is thrown. Therefore, if we do not get a NumberFormatException, we can safely assume that the parseInt() method was able to parse the string into an integer value.

You may want to consider declaring the int variable outside of the try block so that if the NumberFormatException is thrown, you can assign a default value to the variable in the catch block. The code for this technique would be as follows:

int result = 0; try {     result = Integer.parseInt(aString); } catch (NumberFormatException ex) {    result = DEFAULT_VALUE; }





JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net