Java Reference
In-Depth Information
When you run this new version of the program on the new input file, you'll get
one line of output and then Java will throw an exception:
Total hours worked by Erica (id#101) = 825.75
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:819)
at java.util.Scanner.next(Scanner.java:1431)
at java.util.Scanner.nextInt(Scanner.java:2040)
...
The program correctly reads Erica's employee ID and reports it in the println
statement, but then it crashes. Also, notice that the program reports Erica's total hours
worked as 825.75, when the number should be 42.75. Where did it go wrong?
If you compute the difference between the reported sum of 825.75 hours and the
correct sum of 42.75 hours, you'll find it is equal to 783. That number appears in the
data file: It's the employee ID of the second employee, Erin. When the program was
adding up the hours for Erica, it accidentally read Erin's employee ID as more hours
worked by Erica and added this number to the sum. That's also why the exception
occurs—on the second iteration of the loop, the program tries to read an employee ID
for Erin when the next token in the file is her name, not an integer.
The solution is to somehow get the program to stop reading when it gets to the end
of an input line. Unfortunately, there is no easy way to do this with a token-based
approach. The loop asks whether the Scanner has a next double value to read, and
the employee ID looks like a double that can be read. You might try to write a com-
plex test that looks for a double that is not also an integer, but even that won't work
because some of the hours are integers.
To make this program work, you need to write a more sophisticated version that
pays attention to the line breaks. The program must read an entire line of input at a
time and process that line by itself. Recall the main method for the program:
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("hours2.dat"));
process(input);
}
If you incorporate a line-based loop, you'll end up with the following method:
public static void main(String[] args)
throws FileNotFoundException {
Scanner input = new Scanner(new File("hours2.dat"));
while (input.hasNextLine()) {
Search WWH ::




Custom Search