Java Reference
In-Depth Information
10
while
(input.hasNextLine()) {
11 String text = input.nextLine();
12 processLine(text);
13 }
14 }
15
16 // processes the given String (ID, name, and hours worked)
17
public static void
processLine(String text) {
18 Scanner data =
new
Scanner(text);
19
int
id = data.nextInt();
20 String name = data.next();
21
double
sum = 0.0;
22
while
(data.hasNextDouble()) {
23 sum += data.nextDouble();
24 }
25 System.out.println("Total hours worked by " + name +
26 " (id#" + id + ") = " + sum);
27 }
28 }
Notice that the
main
method includes line-based processing to read entire lines of
input from the file. Each such line is passed to the
processLine
method. Each time the
program calls
processLine
, it makes a mini-
Scanner
for just that line of input and
uses token-based processing (calling the methods
nextInt
,
next
, and
nextDouble
).
This new version of the program produces the following output:
Total hours worked by Erica (id#101) = 42.75
Total hours worked by Erin (id#783) = 55.75
Total hours worked by Simone (id#114) = 24.0
Total hours worked by Ryan (id#238) = 31.75
Total hours worked by Kendall (id#156) = 5.5
While this version of the program is a little more complex than the original, it is
much more flexible because it pays attention to line breaks.
In this section we'll explore two advanced topics related to file processing: producing
output files and guaranteeing that files can be read.
All of the programs we've studied so far have sent their output to the console window
by calling
System.out.print
or
System.out.println
. But just as you can read
input from a file instead of reading from the console, you can write output to a file
Search WWH ::
Custom Search