- Home
- Objectives

- XyzWs Study Guides
- Study Guides
- Study Notes
- Resources

- Mock Exams
SCJP Study Guide:
API Contents
Printer-friendly version |
Mail this to a friend
Scanner
The java.util.Scanner is a simple text scanner which can parse primitive types and strings using regular expressions.
The scanner API provides basic input functionality for reading data from the
system console or any data stream. A Scanner breaks its input into
tokens using a delimiter pattern, which by default matches whitespace. The
resulting tokens may then be converted into values of different types using the
various next
methods.
The next() and hasNext() methods and their
primitive-type companion methods (such as nextInt() and hasNextInt())
first skip any input that matches the delimiter pattern, and then attempt to
return the next token. Both hasNext and next methods may
block waiting for further input. Whether a hasNext method blocks has
no connection to whether or not its associated next method will block.
The following example reads a String from standard input and expects a following int value. If you need to process more complex input, then there are also pattern-matching algorithms, available from the java.util.Formatter class.
Scanner s= new Scanner(System.in);
String param= s.next();
int value=s.nextInt();
s.close();
As another example, this code allows long types to be assigned from
entries in a file myNumbers:
Scanner sc = new Scanner(new File("myNumbers"));
while (sc.hasNextLong()) {
long aLong = sc.nextLong();
}
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
prints the following output:
1
2
red
blue
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
System.out.println(result.group(i);
s.close();
The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace.
Scanner Class Constructor Summary
There are few constructors for the Scanner class:
- public Scanner(Readable source) constructs a new Scanner that produces values scanned from a specified character source implementing the Readable interface.
- public Scanner(InputStream source) constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform's default charset.
- public Scanner(InputStream source, String charsetName) constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the specified charset. An IllegalArgumentException exception is thrown, if the specified character set does not exist.
- public Scanner(File source) constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset. A FileNotFoundException is thrown, if source is not found.
- public Scanner(File source, String charsetName) constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the specified charset. A FileNotFoundException is thrown, if source is not found. An IllegalArgumentException exception is thrown, if the specified encoding is not found.
- public Scanner(String source) constructs a new Scanner that produces values scanned from the specified string.
- public Scanner(ReadableByteChannel source) constructs a new Scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the underlying platform's default charset.
- public Scanner(ReadableByteChannel source, String charsetName) constructs a new Scanner that produces values scanned from the specified channel. Bytes from the source are converted into characters using the specified charset. An IllegalArgumentException exception is thrown, if the specified character set does not exist.
Class Mothod Summary
The family of next???()/next???(int radix) and hasNext???()/hasNext???(int radix) methods:
For each of the primitive types there is a corresponding nextXyz() method that returns a value of that type, where Xyz is one of BidDecimal (returns BigDecimal), BigInteger (returns BigInteger), Boolean (returns boolean), Double (returns double), Long (returns long), Byte (returns byte), Float (return float), Short (returns short) and so on, If the string cannot be interpreted as that type, then an InputMismatchException is thrown. There is also a set of hasNextXyz() methods, such as hasNextInt(), that return true or false according to whether the next token matches the specified type.
All of next???(??) methods may throw the following excpetions:
- An InputMismatchException is thrown, if the next token does not match the Integer regular expression, or is out of range.
- A NoSuchElementException exception is thrown, if input is exhausted.
- An IllegalStateException exception is thrown, if the scanner is closed.
All of hasNext???(??) methods may throw an IllegalStateException exception if the scanner is closed.
Scanning String Methods
There four methods return a String from a given scanner. All of them may throw the following two exceptions. A NoSuchElementException exception is thrown, if no more tokens are available. An IllegalStateException exception is thrown, if this scanner is closed.
- public String next() finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
- public String next(String pattern) returns the next token if it matches the pattern constructed from the specified string. If the match is successful, the scanner advances past the input that matched the pattern. An invocation of this method of the form next(pattern) behaves in exactly the same way as the invocation next(Pattern.compile(pattern)).
- public String next(Pattern pattern) returns the next token if it matches the specified pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext(Pattern) returned true. If the match is successful, the scanner advances past the input that matched the pattern.
- public String nextLine() advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.
Each String scanning method has one corresponding hasNext(??) method.