Page 611 - Introduction to Programming with Java: A Problem Solving Approach
P. 611
NumberList Program
The program in Figures 14.14a and 14.14b reads in a list of numbers and calculates the mean. The program compiles and runs successfully most of the time, but it’s not very robust. There are three types of entries that make the program crash. We’ll describe those three entry types, but before you read about them, first try to determine them on your own.
/**************************************************
* NumberListDriver.java
* Dean & Dean
14.11 UnderstandingExceptionMessages 577
*
* This is the driver for the NumberList class.
**************************************************/
public class NumberListDriver
{
public static void main(String[] args)
{
NumberList list = new NumberList();
list.readNumbers();
System.out.println("Mean = " + list.getMean());
} // end main
} // end class NumberListDriver
Apago PDF Enhancer
Figure 14.14a NumberList program driver that drives class in Figure 14.14b User Enters a Non-Integer
In the readNumbers method, note the parseInt call. If the user enters a q, the while loop termi- nates and parseInt is not called. But if the user enters something other than q, parseInt is called. If parseInt is called with a non-integer argument, then parseInt throws a NumberFormatException. And since there’s no try-catch structure the JVM prints a detailed error message and then terminates the program. For example, if the user enters hi, the JVM prints a detailed error message and terminates the program, like this: 4
Sample session:
Enter a whole number (q to quit): hi
thrown exception
Exception in thread "main" java.lang.NumberFormatException:
For input string: "hi"
⎫ at java.lang.NumberFormatException.forInputString( ⎪
NumberFormatException.java:48)
⎪
⎪
⎬
⎪
⎪
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
⎪ at NumberListDriver.main(NumberListDriver.java:13) ⎭
at NumberList.readNumbers(NumberList.java:28)
Identify possible input errors.
c
4 The formatting of the error message may be slightly different, but the information will be similar.
c
a
t
r
r
a
a
l
l
l
ac
l
s
s
t
ta
a
c
ck
ce
k
t
e