Class Scanner: Object Iterator String Closeable
Class Scanner: Object Iterator String Closeable
util
Class Scanner
java.lang.Object
java.util.Scanner
System.in:
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:
Localized numbers
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of
the scanner's locale. A scanner's initial locale is the value returned by
the Locale.getDefault() method; it may be changed via
theuseLocale(java.util.Locale) method. The reset() method will reset the value of the
scanner's locale to the initial locale regardless of whether it was previously changed.
The localized formats are defined in terms of the following parameters, which for a particular locale are taken
from that locale's DecimalFormat object, df, and its
and DecimalFormatSymbols object, dfs.
LocalGroupSeparator
LocalDecimalSeparator
LocalPositivePrefix
The string that appears before a positive number (may be empty), i.e.
LocalPositiveSuffix
The string that appears after a positive number (may be empty), i.e., d
LocalNegativePrefix
The string that appears before a negative number (may be empty), i.e
LocalNegativeSuffix
The string that appears after a negative number (may be empty), i.e.,
LocalNaN
LocalInfinity
The string that represents infinity for floating-point values, i.e., dfs
Number syntax
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following
regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9
in base 10).
ax]
| NonASCIIDigit
ax]
| NonASCIIDigit
Digit+
+]? ( Numeral ) )
LocalDecimalSeparator Digit*
cimalSeparator Digit+
E] [+-]? Digit+ )
? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+ ([pP][-+]?[0-9]+)?
+]? NonNumber )
onNumber
Whitespace is not significant in the above regular expressions.
Since:
1.5
Constructor Summary
Constructors
Constructor and Description
Scanner(File source)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(File source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(InputStream source)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(InputStream source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified input stream.
Scanner(Path source)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(Path source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified file.
Scanner(Readable source)
Constructs a new Scanner that produces values scanned from the specified source.
Scanner(ReadableByteChannel source)
Constructs a new Scanner that produces values scanned from the specified channel.
Scanner(ReadableByteChannel source, String charsetName)
Constructs a new Scanner that produces values scanned from the specified channel.
Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Method Summary
Methods
Modifier and Type
void
close()
Closes this scanner.
Pattern
String
delimiter()
Returns the Pattern this Scanner is currently using
findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern
String
findInLine(String pattern)
Attempts to find the next occurrence of a pattern constructed
String
findWithinHorizon(Pattern pattern,
String
findWithinHorizon(String pattern,
Attempts to find the next occurrence of a pattern constructed
boolean
hasNext()
Returns true if this scanner has another token in its input.
boolean
hasNext(Pattern pattern)
boolean
hasNext(String pattern)
boolean
hasNextBigDecimal()
boolean
hasNextBigInteger()
boolean
hasNextBigInteger(int radix)
boolean
hasNextBoolean()
boolean
hasNextByte()
boolean
hasNextByte(int radix)
boolean
hasNextDouble()
boolean
hasNextFloat()
boolean
hasNextInt()
boolean
hasNextInt(int radix)
boolean
hasNextLine()
boolean
hasNextLong()
boolean
hasNextLong(int radix)
boolean
hasNextShort()
boolean
hasNextShort(int radix)
IOException
Locale
ioException()
Returns the IOException last thrown by this Scann
locale()
MatchResult
match()
String
next()
Finds and returns the next complete token from this scanner.
String
next(Pattern pattern)
Returns the next token if it matches the specified pattern.
String
next(String pattern)
BigDecimal
nextBigDecimal()
Scans the next token of the input as a BigDecimal.
BigInteger
nextBigInteger()
Scans the next token of the input as a BigInteger.
BigInteger
boolean
nextBigInteger(int radix)
Scans the next token of the input as a BigInteger.
nextBoolean()
Scans the next token of the input into a boolean value and ret
byte
nextByte()
Scans the next token of the input as a byte.
byte
nextByte(int radix)
Scans the next token of the input as a byte.
double
nextDouble()
Scans the next token of the input as a double.
float
nextFloat()
Scans the next token of the input as a float.
int
nextInt()
Scans the next token of the input as an int.
int
nextInt(int radix)
Scans the next token of the input as an int.
String
nextLine()
Advances this scanner past the current line and returns the in
long
nextLong()
Scans the next token of the input as a long.
long
nextLong(int radix)
Scans the next token of the input as a long.
short
nextShort()
Scans the next token of the input as a short.
short
nextShort(int radix)
radix()
int
remove()
void
Scanner
reset()
Resets this scanner.
Scanner
skip(Pattern pattern)
Scanner
skip(String pattern)
String
toString()
Returns the string representation of this Scanner.
Scanner
useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
Scanner
useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed
Scanner
useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
Scanner
useRadix(int radix)
Sets this scanner's default radix to the specified radix.
Constructor Detail
Scanner
public Scanner(Readable source)
Constructs a new Scanner that produces values scanned from the specified source.
Parameters:
Scanner
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.
Parameters:
Scanner
Parameters:
Throws:
Scanner
Parameters:
Scanner
Parameters:
Scanner
Parameters:
Scanner
Parameters:
Scanner
public Scanner(String source)
Constructs a new Scanner that produces values scanned from the specified string.
Parameters:
Scanner
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.
Parameters:
Scanner
Parameters:
Throws:
Method Detail
close
public void close()
Closes this scanner.
If this scanner has not yet been closed then if its underlying readable also implements
the Closeable interface then the readable's close method will be invoked. If this scanner is already closed
then invoking this method will have no effect.
Attempting to perform search operations after a scanner has been closed will result in
an IllegalStateException.
Specified by:
ioException
public IOException ioException()
Returns the IOException last thrown by this Scanner's underlying Readable. This method
returns null if no such exception exists.
Returns:
the last exception thrown by this scanner's readable
delimiter
public Pattern delimiter()
Returns the Pattern this Scanner is currently using to match delimiters.
Returns:
this scanner's delimiting pattern.
useDelimiter
public Scanner useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
Parameters:
useDelimiter
public Scanner useDelimiter(String pattern)
Sets this scanner's delimiting pattern to a pattern constructed from the specified
String.
An invocation of this method of the form useDelimiter(pattern) behaves in exactly the same way as
the invocation useDelimiter(Pattern.compile(pattern)).
Invoking the reset() method will set the scanner's delimiter to the default.
Parameters:
locale
public Locale locale()
Returns this scanner's locale.
A scanner's locale affects many elements of its default primitive matching regular expressions; see localized
numbers above.
Returns:
this scanner's locale
useLocale
public Scanner useLocale(Locale locale)
Sets this scanner's locale to the specified locale.
A scanner's locale affects many elements of its default primitive matching regular expressions; see localized
numbers above.
Invoking the reset() method will set the scanner's locale to the initial locale.
Parameters:
radix
public int radix()
Returns this scanner's default radix.
A scanner's radix affects elements of its default number matching regular expressions; see localized
numbers above.
Returns:
the default radix of this scanner
useRadix
public Scanner useRadix(int radix)
Sets this scanner's default radix to the specified radix.
A scanner's radix affects elements of its default number matching regular expressions; see localized
numbers above.
If the radix is less than Character.MIN_RADIX or greater than Character.MAX_RADIX, then
an IllegalArgumentException is thrown.
Invoking the reset() method will set the scanner's radix to
Parameters:
10.
Throws:
match
public MatchResult match()
Returns the match result of the last scanning operation performed by this scanner. This method
throws IllegalStateException if no match has been performed, or if the last match was not
successful.
The various nextmethods of Scanner make a match result available if they complete without throwing an
exception. For instance, after an invocation of the nextInt() method that returned an int, this method returns
a MatchResult for the search of the Integer regular expression defined above. Similarly
the findInLine(java.lang.String), findWithinHorizon(java.lang.String,
int), and skip(java.util.regex.Pattern) methods will make a match available if they
succeed.
Returns:
a match result for the last match operation
Throws:
toString
public String toString()
Returns the string representation of this Scanner. The string representation of a
information that may be useful for debugging. The exact format is unspecified.
Scanner contains
Overrides:
hasNext
public boolean hasNext()
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan.
The scanner does not advance past any input.
Specified by:
Throws:
Iterator
next
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 ofhasNext() returned true.
Specified by:
Throws:
Iterator
remove
public void remove()
The remove operation is not supported by this implementation of
Iterator.
Specified by:
Iterator
hasNext
public boolean hasNext(String pattern)
Returns true if the next token matches the pattern constructed from the specified string. The scanner does not
advance past any input.
An invocation of this method of the form hasNext(pattern) behaves in exactly the same way as the
invocation hasNext(Pattern.compile(pattern)).
Parameters:
Throws:
next
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)).
Parameters:
Throws:
hasNext
public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed
by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not
advance past any input.
Parameters:
Throws:
next
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.
Parameters:
Throws:
hasNextLine
public boolean hasNextLine()
Returns true if there is another line in the input of this scanner. This method may block while waiting for input.
The scanner does not advance past any input.
Returns:
true if and only if this scanner has another line of input
Throws:
nextLine
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.
Returns:
the line that was skipped
Throws:
findInLine
Parameters:
Throws:
findInLine
public String findInLine(Pattern pattern)
Attempts to find the next occurrence of the specified pattern ignoring delimiters. If the pattern is found before the
next line separator, the scanner advances past the input that matched and returns the string that matched the
pattern. If no such pattern is detected in the input up to the next line separator, then null is returned and the
scanner's position is unchanged. This method may block waiting for input that matches the pattern.
Since this method continues to search through the input looking for the specified pattern, it may buffer all of the
input searching for the desired token if no line separators are present.
Parameters:
Throws:
findWithinHorizon
Parameters:
Returns:
the text that matched the specified pattern
Throws:
findWithinHorizon
Parameters:
Throws:
skip
public Scanner skip(Pattern pattern)
Skips input that matches the specified pattern, ignoring delimiters. This method will skip input if an anchored
match of the specified pattern succeeds.
If a match to the specified pattern is not found at the current position, then no input is skipped and
a NoSuchElementException is thrown.
Since this method seeks to match the specified pattern starting at the scanner's current position, patterns that
can match a lot of input (".*", for example) may cause the scanner to buffer a large amount of input.
Note that it is possible to skip something without risking a NoSuchElementException by using a pattern
that can match nothing, e.g., sc.skip("[ \t]*").
Parameters:
Throws:
skip
public Scanner skip(String pattern)
Skips input that matches a pattern constructed from the specified string.
An invocation of this method of the form skip(pattern) behaves in exactly the same way as the
invocation skip(Pattern.compile(pattern)).
Parameters:
Throws:
hasNextBoolean
public boolean hasNextBoolean()
Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case
insensitive pattern created from the string "true|false". The scanner does not advance past the input that
matched.
Returns:
true if and only if this scanner's next token is a valid boolean value
Throws:
nextBoolean
Returns:
the boolean scanned from the input
Throws:
hasNextByte
public boolean hasNextByte()
Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using
the nextByte() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid byte value
Throws:
hasNextByte
public boolean hasNextByte(int radix)
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using
the nextByte() method. The scanner does not advance past any input.
Parameters:
Throws:
nextByte
public byte nextByte()
Scans the next token of the input as a
byte.
An invocation of this method of the form nextByte() behaves in exactly the same way as the
invocation nextByte(radix), where radix is the default radix of this scanner.
Returns:
the byte scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
nextByte
public byte nextByte(int radix)
Scans the next token of the input as a byte. This method will throw InputMismatchException if the
next token cannot be translated into a valid byte value as described below. If the translation is successful, the
scanner advances past the input that matched.
If the next token matches the Integer regular expression defined above then the token is converted into
a byte value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then
mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Byte.parseByte with the specified radix.
Parameters:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
hasNextShort
public boolean hasNextShort()
Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using
the nextShort() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid short value in the default radix
Throws:
hasNextShort
public boolean hasNextShort(int radix)
Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix
using the nextShort() method. The scanner does not advance past any input.
Parameters:
Throws:
nextShort
public short nextShort()
Scans the next token of the input as a
short.
An invocation of this method of the form nextShort() behaves in exactly the same way as the
invocation nextShort(radix), where radix is the default radix of this scanner.
Returns:
the short scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
nextShort
public short nextShort(int radix)
Scans the next token of the input as a short. This method will throw InputMismatchException if the
next token cannot be translated into a valid short value as described below. If the translation is successful, the
scanner advances past the input that matched.
If the next token matches the Integer regular expression defined above then the token is converted into
a short value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then
mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Short.parseShort with the specified radix.
Parameters:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
hasNextInt
public boolean hasNextInt()
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using
the nextInt() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid int value
Throws:
hasNextInt
public boolean hasNextInt(int radix)
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using
the nextInt() method. The scanner does not advance past any input.
Parameters:
Throws:
nextInt
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt() behaves in exactly the same way as the
invocation nextInt(radix), where radix is the default radix of this scanner.
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
nextInt
public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the
next token cannot be translated into a valid int value as described below. If the translation is successful, the
scanner advances past the input that matched.
If the next token matches the Integer regular expression defined above then the token is converted into
an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then
mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Integer.parseInt with the specified radix.
Parameters:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
hasNextLong
public boolean hasNextLong()
Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using
the nextLong() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid long value
Throws:
hasNextLong
public boolean hasNextLong(int radix)
Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using
the nextLong() method. The scanner does not advance past any input.
Parameters:
Throws:
nextLong
public long nextLong()
Scans the next token of the input as a
long.
An invocation of this method of the form nextLong() behaves in exactly the same way as the
invocation nextLong(radix), where radix is the default radix of this scanner.
Returns:
the long scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
nextLong
public long nextLong(int radix)
Scans the next token of the input as a long. This method will throw InputMismatchException if the
next token cannot be translated into a valid long value as described below. If the translation is successful, the
scanner advances past the input that matched.
If the next token matches the Integer regular expression defined above then the token is converted into
a long value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then
mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Long.parseLong with the specified radix.
Parameters:
Returns:
the long scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
hasNextFloat
public boolean hasNextFloat()
Returns true if the next token in this scanner's input can be interpreted as a float value using
the nextFloat() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid float value
Throws:
nextFloat
public float nextFloat()
Scans the next token of the input as a float. This method will throw InputMismatchException if the
next token cannot be translated into a valid float value as described below. If the translation is successful, the
scanner advances past the input that matched.
If the next token matches the Float regular expression defined above then the token is converted into
a float value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then
mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Float.parseFloat. If the token matches the localized NaN or infinity strings, then either "Nan" or
"Infinity" is passed to Float.parseFloat as appropriate.
Returns:
the float scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or
is out of range
hasNextDouble
public boolean hasNextDouble()
Returns true if the next token in this scanner's input can be interpreted as a double value using
the nextDouble() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid double value
Throws:
nextDouble
public double nextDouble()
Scans the next token of the input as a double. This method will throw InputMismatchException if
the next token cannot be translated into a valid double value. If the translation is successful, the scanner
advances past the input that matched.
If the next token matches the Float regular expression defined above then the token is converted into
a double value as if by removing all locale specific prefixes, group separators, and locale specific suffixes,
then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the
locale specific negative prefixes and suffixes were present, and passing the resulting string
to Double.parseDouble. If the token matches the localized NaN or infinity strings, then either "Nan" or
"Infinity" is passed to Double.parseDouble as appropriate.
Returns:
the double scanned from the input
Throws:
InputMismatchException - if the next token does not match the Float regular expression, or
is out of range
hasNextBigInteger
public boolean hasNextBigInteger()
Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix
using the nextBigInteger() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid
BigInteger
Throws:
hasNextBigInteger
public boolean hasNextBigInteger(int radix)
Returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified
radix using the nextBigInteger() method. The scanner does not advance past any input.
Parameters:
BigInteger
Throws:
nextBigInteger
public BigInteger nextBigInteger()
Scans the next token of the input as a
BigInteger.
An invocation of this method of the form nextBigInteger() behaves in exactly the same way as the
invocation nextBigInteger(radix), where radix is the default radix of this scanner.
Returns:
the BigInteger scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
nextBigInteger
public BigInteger nextBigInteger(int radix)
Scans the next token of the input as a
BigInteger.
If the next token matches the Integer regular expression defined above then the token is converted into
a BigInteger value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via
the Character.digit, and passing the resulting string to the BigInteger(String,
int) constructor with the specified radix.
Parameters:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression,
or is out of range
hasNextBigDecimal
public boolean hasNextBigDecimal()
Returns true if the next token in this scanner's input can be interpreted as a BigDecimal using
the nextBigDecimal() method. The scanner does not advance past any input.
Returns:
true if and only if this scanner's next token is a valid
BigDecimal
Throws:
nextBigDecimal
public BigDecimal nextBigDecimal()
Scans the next token of the input as a
BigDecimal.
If the next token matches the Decimal regular expression defined above then the token is converted into
a BigDecimal value as if by removing all group separators, mapping non-ASCII digits into ASCII digits via
the Character.digit, and passing the resulting string to the BigDecimal(String) constructor.
Returns:
the BigDecimal scanned from the input
Throws:
InputMismatchException - if the next token does not match the Decimal regular expression,
or is out of range
reset
public Scanner reset()
Resets this scanner.
Resetting a scanner discards all of its explicit state information which may have been changed by invocations
of useDelimiter(java.util.regex.Pattern), useLocale(java.util.Locale),
or useRadix(int).
An invocation of this method of the form
invocation
scanner.useDelimiter("\\p{javaWhitespace}+")
.useLocale(Locale.getDefault())
.useRadix(10);
Returns:
this scanner
Since:
1.6