Java Reference
In-Depth Information
The Scanner object can do better than this. In addition to the hasNext() method that checks whether
a token of any kind is available, you have methods such as hasNextInt() and hasNextDouble() for
testing for the availability of any of the types that you can read with methods such as nextInt() and nex-
tDouble() . This enables you to code so that you can process tokens of various types, even when you don't
know ahead of time the sequence in which they will be received. For example:
while(fileScan.hasNext()) {
if(fileScan.hasNextInt()) {
// Process integer input...
} else if(fileScan.hasNextDouble()) {
// Process floating-point input...
} else if(fileScan.hasNextBoolean()) {
// Process boolean input...
}
}
The while loop continues as long as there are tokens of any kind available from the scanner. The if
statements within the loop decide how the next token is to be processed, assuming it is one of the ones that
you are interested in. If you want to skip tokens that you don't want to process within the loop, you call the
next() method for fileScan .
Defining Your Own Patterns for Tokens
The Scanner class provides a way for you to specify how a token should be recognized. You use one of two
overloaded versions of the next() method to do this. One version accepts an argument of type Pattern that
you produce by compiling a regular expression in the way you saw earlier in this chapter. The other accepts
an argument of type String that specifies a regular expression that identifies the token. In both cases the
token is returned as type String .
There are also overloaded versions of the hasNext() method that accept either a Pattern argument, or
a String object containing a regular expression that identifies a token. You use these to test for tokens of
your own specification. You could see these in action in an example that scans a string for a token specified
by a simple pattern.
TRY IT OUT: Scanning a String
This example scans a string looking for occurrences of "had" :
import java.util.Scanner;
import java.util.regex.Pattern;
public class ScanString {
Search WWH ::




Custom Search