Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

Chapter 18: java.util Part 2: More Utility Classes 541


This next line creates aScannerthat reads from standard input, which is the keyboard
by default:


Scanner conin = new Scanner(System.in);


This works becauseSystem.inis an object of typeInputStream. Thus, the call to the
constructor maps toScanner(InputStream).
The next sequence creates aScannerthat reads from a string.


String instr = "10 99.88 scanning is easy.";
Scanner conin = new Scanner(instr);


Scanning Basics

Once you have created aScanner, it is a simple matter to use it to read formatted input.
In general, aScannerreadstokensfrom the underlying source that you specified when the
Scannerwas created. As it relates toScanner, a token is a portion of input that is delineated
by a set of delimiters, which is whitespace by default. A token is read by matching it with a
particularregular expression,which defines the format of the data. AlthoughScannerallows
you to define the specific type of expression that its next input operation will match, it includes
many predefined patterns, which match the primitive types, such asintanddouble, and
strings. Thus, often you won’t need to specify a pattern to match.
In general, to useScanner, follow this procedure:



  1. Determine if a specific type of input is available by calling one ofScanner’s
    hasNextXmethods, whereXis the type of data desired.

  2. If input is available, read it by calling one ofScanner’snextXmethods.

  3. Repeat the process until input is exhausted.


As the preceding indicates,Scannerdefines two sets of methods that enable you to read
input. The first are thehasNextXmethods, which are shown in Table 18-15. These methods
determine if the specified type of input is available. For example, callinghasNextInt( )returns
trueonly if the next token to be read is an integer. If the desired data is available, then you
read it by calling one ofScanner’snextXmethods, which are shown in Table 18-16. For
example, to read the next integer, callnextInt( ). The following sequence shows how to read
a list of integers from the keyboard.


Scanner conin = new Scanner(System.in);
int i;


// Read a list of integers.
while(conin.hasNextInt()) {
i = conin.nextInt();
// ...
}

Free download pdf