Java Reference
In-Depth Information
This program produces the following output:
18.4
17.9
8.3
2.9
Notice that the program produces four lines of output because there are four num-
bers in the String used to construct the Scanner .
When a file requires a combination of line-based and token-based processing, you
can construct a String -based Scanner for each line of the input file. Using this
approach, you end up with a lot of Scanner objects. You have a Scanner object that
is keeping track of the input file, and you use that Scanner to read entire lines of
input. In addition, each time you read a line of text from the file, you construct a
mini- Scanner for just that line of input. You can then use token-based processing for
these mini- Scanner objects, because each contains just a single line of data.
This combination of line-based and token-based processing is powerful. You will
find that you can use this approach (and slight variations on it) to process a large
variety of input files. To summarize, this approach involves a two-step process:
1. Break the file into lines with a Scanner using calls on hasNextLine and
nextLine .
2. Break apart each line by constructing a Scanner just for that line of input and
making calls on token-based methods like hasNext and next .
Following this approach, if you have a file composed of n lines of input, you end
up constructing n
1 different Scanner objects-one for each of the n individual
lines (step 2) and one extra Scanner that is used to process the overall file line by
line (step 1).
In the HoursWorked program, each input line contains information for a single
employee. Processing the input line involves making a Scanner for the line and then
reading its various parts (employee ID, name, hours) in a token-based manner. You
can put this all together into a new version of the program:
1 // Variation of HoursWorked that includes employee IDs.
2
3 import java.io.*;
4 import java.util.*;
5
6 public class HoursWorked2 {
7 public static void main(String[] args)
8 throws FileNotFoundException {
9 Scanner input = new Scanner( new File("hours2.dat"));
Search WWH ::




Custom Search