Java Reference
In-Depth Information
That means you can read them with a call on the
next
method. As a result, the
while
loop test involves seeing whether there is another name in the input file:
while (input.hasNext()) {
process next person.
}
So, how do you process each person? You have to read that person's name and
then read that person's list of hours. If you look at the sample input file, you will see
that the list of hours is not always the same length. For example, some employees
worked on five days, while others worked only two or three days. This unevenness is
a common occurrence in input files. You can deal with it by using a nested loop. The
outer loop will handle one person at a time and the inner loop will handle one num-
ber at a time. The task is a fairly straightforward cumulative sum:
double sum = 0.0;
while (input.hasNextDouble()) {
sum += input.nextDouble();
}
When you put the parts of the program together, you end up with the following
complete program:
1 // This program reads an input file of hours worked by various
2 // employees and reports the total hours worked by each.
3
4
import
java.io.*;
5
import
java.util.*;
6
7
public class
HoursWorked {
8
public static void
main(String[] args)
9
throws
FileNotFoundException {
10 Scanner input =
new
Scanner(
new
File("hours.dat"));
11
process(input);
12 }
13
14
public static void
process(Scanner input) {
15
while
(input.hasNext()) {
16 String name = input.next();
17
double
sum = 0.0;
18
while
(input.hasNextDouble()) {
19
sum += input.nextDouble();
20 }
21 System.out.println("Total hours worked by " + name
22 + " = " + sum);
Search WWH ::
Custom Search