The Scanner
class, introduced with J2SE 5.0, is a very useful new class that
can parse text for primitive types and substrings using regular
expressions. It can obtain the text from sources such as a String
object, an InputStream,
a File,
and any class that implements the Readable
interface.
The Scanner
splits input into substrings, or tokens, separated by delimiters,
which by default consist of any white space. The tokens can then
be obtained as strings or as primitive types if that is what they
represent.
For example, the following code snippet shows how
to read an integer from the keyboard
Scanner
scanner = new Scanner (System.in);
int i = scanner.nextInt ();
For each of the primitive types there is a corresponding
nextXxx()
method that returns a value of that type. If the string cannot
be interpreted as that type, then an InputMismatchException
is thrown.
There is also a set of hasNextXxx()
methods, such as hasNextInt(),
that return true
or false
according to whether the next token matches the specified type.
The program ScanConsoleApp
demonstrates how to read
int, float,
and double
values from the keyboard.
ScanConsoleApp.java |
import
java.io.*;
import java.util.*;
/** Demonstrate the Scanner class for input of numbers.**/
public class ScanConsoleApp
{
public static void main (String arg[]) {
// Create a scanner to read from
keyboard
Scanner scanner = new Scanner (System.in);
try {
System.out.printf ("Input
int (e.g. %4d): ",3501);
int int_val = scanner.nextInt
();
System.out.println ("
You entered " + int_val +"\n");
System.out.printf ("Input
float (e.g. %5.2f): ", 2.43);
float float_val = scanner.nextFloat
();
System.out.println ("
You entered " + float_val +"\n");
System.out.printf ("Input
double (e.g. %6.3e): ",4.943e15);
double double_val =
scanner.nextDouble ();
System.out.println ("
You entered " + double_val +"\n");
}
catch (InputMismatchException
e) {
System.out.println ("Mismatch
exception:" + e );
}
} // main
} // class ScanConsoleApp
|
A session with this program goes as follows:
Input
int (e.g. 3501): 23431
You entered 23431
Input float (e.g. 2.43): 1.2343
You entered 1.2343
Input double (e.g. 4.943e+15): -2.34e4
You entered -23400.0
There are a number of other useful methods in the
Scanner
class such as skip()
to jump over input, useDelimiter()
defines a delimiter in place of the default white space, and findInLine()
to search for substrings.
The Scanner
class uses tools from the java.util.regex
package, which deals with pattern matching using regular expressions.
We don't have space here to describe these very powerful text
matching tools but you can find more info in the Java 2 API Specifications.
References and Web
Resources
-
java.util.Scanner
- class specifications for J2SE5.0. Example codes are included
in the introduction.
-
-
Latest update: Nov. 12, 2004
|