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 ...

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.