Java Reference
In-Depth Information
String text = input.nextLine();
processLine(text);
}
}
Reading the file line by line guarantees that you don't accidentally combine data
for two employees. The downside to this approach is that you have to write a method
called
processLine
that takes a
String
as a parameter, and you have to pull apart
that
String
. It contains the employee ID, followed by the employee name, followed
by the numbers indicating how many hours the employee worked on different days.
In other words, the input line is composed of several pieces (tokens) that you want to
process piece by piece. It's much easier to process this data in a token-based manner
than to have it in a
String
.
Fortunately, there is a convenient way to do this. You can construct a
Scanner
object from an individual
String
. Remember that just as you can attach a faucet to
different sources of water (a faucet in a house attached to city or well water versus a
faucet on an airplane attached to a tank of water), you can attach a
Scanner
to differ-
ent sources of input. You've seen how to attach it to the console (
System.in
) and to
a file (passing a
File
object). You can also attach it to an individual
String
. For
example, consider the following line of code:
Scanner input = new Scanner("18.4 17.9 8.3 2.9");
This code constructs a
Scanner
that gets its input from the
String
used to con-
struct it. This
Scanner
has an input cursor just like a
Scanner
linked to a file.
Initially the input cursor is positioned at the first character in the
String
, and it
moves forward as you read tokens from the
Scanner
.
The following short program demonstrates this solution:
1 // Simple example of a Scanner reading from a String.
2
3
import
java.util.*;
4
5
public class
StringScannerExample {
6
public static void
main(String[] args) {
7 Scanner input =
new
Scanner("18.4 17.9 8.3 2.9");
8
while
(input.hasNextDouble()) {
9
double
next = input.nextDouble();
10 System.out.println(next);
11 }
12 }
13 }
Search WWH ::
Custom Search