Activity 4 — Catching an exception A common problem when processing numeric input from users is that they enter real values, or values with comma’s etc. when, say, an integer is required. So for example a program might request an age from the user (expecting an integer), and a small child might enter ‘3.5’ or ‘3 and a half’. The application below uses a Swing dialogue box to request and get input from the user. This showInputDialogue() method returns the value entered by the user as a String , whether we wanted a String , or char , or int or double or whatever. One convenient way to convert from a String to an int is to use the class method parseInt() provided by the String class. This method converts from a String . , such as ‘21’ (i.e. character ‘2’ followed by character ‘1’) to the int 21. When the application is run it first displays a message in the console window (via System.out.println() ): Age parsing application Then the application presents to the user an input dialogue, requesting their age: 
Then the application displays the current age (having parsed it to an int), and the age of the person next birthday. Then the application terminates:
The problem occurs if what the user enters is not a valid integer (say 4.5). Then the application crashes with the following messages: 
The listing of the application is as follows: public class Exception1 { public static void main( String args[] ) { String ageString; int age; System.out.println("Age parsing application"); ageString = JOptionPane.showInputDialog(null, "Enter age (1-100)", "Entry of age", JOptionPane.QUESTION_MESSAGE); age = Integer.parseInt( ageString ); int ageNextBirthday = (age + 1); System.out.println("Age now : " + age); System.out.println("Age next birthday: " + ageNextBirthday); System.exit(0); } } // class
Find out about parseInt() and the exception it throws when its String is not a valid, and amend the application to display the following message before terminating if the age entered is invalid: sorry - your age entry of ‘<age>‘ is not a valid integer where <age> is whatever the user entered. So if the user entered ‘4.5’ the message would be: sorry - your age entry of ‘4.5’ is not a valid integer Discussion/Suggested solution to Activity 4 Back to content Back to top 
RITSEC - Global Campus Copyright ?1999 RITSEC- Middlesex University. All rights reserved. webmaster@globalcampus.com.eg |