Java Reference
In-Depth Information
Scanner
objects are designed for file processing in a forward manner. They pro-
vide a great deal of flexibility for looking ahead in an input file, but no support for
reading the input backwards. There are no “previous” methods, and there's no mech-
anism for resetting a
Scanner
back to the beginning of the input. Instead, you would
have to construct a new
Scanner
object that would be positioned at the beginning
of the file. We will see an example of this technique in the case study at the end of
the chapter.
Novices are sometimes surprised that the input cursor for a
Scanner
does not reset to
the beginning of the file when it is passed as a parameter to a method. For example,
consider the following variation of the
ShowSum1
program. It has a method that takes
a
Scanner
as input and an integer specifying how many numbers to process:
1 // Demonstrates a Scanner as a parameter to a method that
2 // can consume an arbitrary number of tokens.
3
4
import
java.io.*;
5
import
java.util.*;
6
7
public class
ShowSum3 {
8
public static void
main(String[] args)
9
throws
FileNotFoundException {
10 Scanner input =
new
Scanner(
new
File("numbers.dat"));
11 processTokens(input, 2);
12 processTokens(input, 3);
13 processTokens(input, 2);
14 }
15
16
public static void
processTokens(Scanner input,
int
n) {
17
double
sum = 0.0;
18
for
(
int
i = 1; i <= n; i++) {
19
double
next = input.nextDouble();
20
System.out.println("number " + i + " = " + next);
21
sum += next;
22 }
23 System.out.println("Sum = " + sum);
24 System.out.println();
25 }
26 }
The
main
method creates a
Scanner
object that is tied to the
numbers.dat
file. It
then calls the
processTokens
method several times, indicating the number of tokens
Search WWH ::
Custom Search