|
Java example source code file (Scanner.java)
The Scanner.java Java example source code/* * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; import java.nio.file.Path; import java.nio.file.Files; import java.util.regex.*; import java.io.*; import java.math.*; import java.nio.*; import java.nio.channels.*; import java.nio.charset.*; import java.text.*; import java.util.Locale; import sun.misc.LRUCache; /** * A simple text scanner which can parse primitive types and strings using * regular expressions. * * <p>A
Readable . This method
* returns <code>null if no such exception exists.
*
* @return the last exception thrown by this scanner's readable
*/
public IOException ioException() {
return lastException;
}
/**
* Returns the <code>Pattern this Scanner is currently
* using to match delimiters.
*
* @return this scanner's delimiting pattern.
*/
public Pattern delimiter() {
return delimPattern;
}
/**
* Sets this scanner's delimiting pattern to the specified pattern.
*
* @param pattern A delimiting pattern
* @return this scanner
*/
public Scanner useDelimiter(Pattern pattern) {
delimPattern = pattern;
return this;
}
/**
* Sets this scanner's delimiting pattern to a pattern constructed from
* the specified <code>String.
*
* <p> An invocation of this method of the form
* <tt>useDelimiter(pattern) behaves in exactly the same way as the
* invocation <tt>useDelimiter(Pattern.compile(pattern)).
*
* <p> Invoking the {@link #reset} method will set the scanner's delimiter
* to the <a href= "#default-delimiter">default.
*
* @param pattern A string specifying a delimiting pattern
* @return this scanner
*/
public Scanner useDelimiter(String pattern) {
delimPattern = patternCache.forName(pattern);
return this;
}
/**
* Returns this scanner's locale.
*
* <p>A scanner's locale affects many elements of its default
* primitive matching regular expressions; see
* <a href= "#localized-numbers">localized numbers above.
*
* @return this scanner's locale
*/
public Locale locale() {
return this.locale;
}
/**
* Sets this scanner's locale to the specified locale.
*
* <p>A scanner's locale affects many elements of its default
* primitive matching regular expressions; see
* <a href= "#localized-numbers">localized numbers above.
*
* <p>Invoking the {@link #reset} method will set the scanner's locale to
* the <a href= "#initial-locale">initial locale.
*
* @param locale A string specifying the locale to use
* @return this scanner
*/
public Scanner useLocale(Locale locale) {
if (locale.equals(this.locale))
return this;
this.locale = locale;
DecimalFormat df =
(DecimalFormat)NumberFormat.getNumberInstance(locale);
DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
// These must be literalized to avoid collision with regex
// metacharacters such as dot or parenthesis
groupSeparator = "\\" + dfs.getGroupingSeparator();
decimalSeparator = "\\" + dfs.getDecimalSeparator();
// Quoting the nonzero length locale-specific things
// to avoid potential conflict with metacharacters
nanString = "\\Q" + dfs.getNaN() + "\\E";
infinityString = "\\Q" + dfs.getInfinity() + "\\E";
positivePrefix = df.getPositivePrefix();
if (positivePrefix.length() > 0)
positivePrefix = "\\Q" + positivePrefix + "\\E";
negativePrefix = df.getNegativePrefix();
if (negativePrefix.length() > 0)
negativePrefix = "\\Q" + negativePrefix + "\\E";
positiveSuffix = df.getPositiveSuffix();
if (positiveSuffix.length() > 0)
positiveSuffix = "\\Q" + positiveSuffix + "\\E";
negativeSuffix = df.getNegativeSuffix();
if (negativeSuffix.length() > 0)
negativeSuffix = "\\Q" + negativeSuffix + "\\E";
// Force rebuilding and recompilation of locale dependent
// primitive patterns
integerPattern = null;
floatPattern = null;
return this;
}
/**
* Returns this scanner's default radix.
*
* <p>A scanner's radix affects elements of its default
* number matching regular expressions; see
* <a href= "#localized-numbers">localized numbers above.
*
* @return the default radix of this scanner
*/
public int radix() {
return this.defaultRadix;
}
/**
* Sets this scanner's default radix to the specified radix.
*
* <p>A scanner's radix affects elements of its default
* number matching regular expressions; see
* <a href= "#localized-numbers">localized numbers above.
*
* <p>If the radix is less than Character.MIN_RADIX
* or greater than <code>Character.MAX_RADIX, then an
* <code>IllegalArgumentException is thrown.
*
* <p>Invoking the {@link #reset} method will set the scanner's radix to
* <code>10.
*
* @param radix The radix to use when scanning numbers
* @return this scanner
* @throws IllegalArgumentException if radix is out of range
*/
public Scanner useRadix(int radix) {
if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX))
throw new IllegalArgumentException("radix:"+radix);
if (this.defaultRadix == radix)
return this;
this.defaultRadix = radix;
// Force rebuilding and recompilation of radix dependent patterns
integerPattern = null;
return this;
}
// The next operation should occur in the specified radix but
// the default is left untouched.
private void setRadix(int radix) {
if (this.radix != radix) {
// Force rebuilding and recompilation of radix dependent patterns
integerPattern = null;
this.radix = radix;
}
}
/**
* Returns the match result of the last scanning operation performed
* by this scanner. This method throws <code>IllegalStateException
* if no match has been performed, or if the last match was
* not successful.
*
* <p>The various next methods of Scanner
* make a match result available if they complete without throwing an
* exception. For instance, after an invocation of the {@link #nextInt}
* method that returned an int, this method returns a
* <code>MatchResult for the search of the
* <a href="#Integer-regex">Integer regular expression
* defined above. Similarly the {@link #findInLine},
* {@link #findWithinHorizon}, and {@link #skip} methods will make a
* match available if they succeed.
*
* @return a match result for the last match operation
* @throws IllegalStateException If no match result is available
*/
public MatchResult match() {
if (!matchValid)
throw new IllegalStateException("No match result available");
return matcher.toMatchResult();
}
/**
* <p>Returns the string representation of this Scanner . The
* string representation of a <code>Scanner contains information
* that may be useful for debugging. The exact format is unspecified.
*
* @return The string representation of this scanner
*/
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("java.util.Scanner");
sb.append("[delimiters=" + delimPattern + "]");
sb.append("[position=" + position + "]");
sb.append("[match valid=" + matchValid + "]");
sb.append("[need input=" + needInput + "]");
sb.append("[source closed=" + sourceClosed + "]");
sb.append("[skipped=" + skipped + "]");
sb.append("[group separator=" + groupSeparator + "]");
sb.append("[decimal separator=" + decimalSeparator + "]");
sb.append("[positive prefix=" + positivePrefix + "]");
sb.append("[negative prefix=" + negativePrefix + "]");
sb.append("[positive suffix=" + positiveSuffix + "]");
sb.append("[negative suffix=" + negativeSuffix + "]");
sb.append("[NaN string=" + nanString + "]");
sb.append("[infinity string=" + infinityString + "]");
return sb.toString();
}
/**
* 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.
*
* @return true if and only if this scanner has another token
* @throws IllegalStateException if this scanner is closed
* @see java.util.Iterator
*/
public boolean hasNext() {
ensureOpen();
saveState();
while (!sourceClosed) {
if (hasTokenInBuffer())
return revertState(true);
readInput();
}
boolean result = hasTokenInBuffer();
return revertState(result);
}
/**
* 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 {@link #hasNext} returned
* <code>true.
*
* @return the next token
* @throws NoSuchElementException if no more tokens are available
* @throws IllegalStateException if this scanner is closed
* @see java.util.Iterator
*/
public String next() {
ensureOpen();
clearCaches();
while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput)
readInput();
else
throwFor();
}
}
/**
* The remove operation is not supported by this implementation of
* <code>Iterator.
*
* @throws UnsupportedOperationException if this method is invoked.
* @see java.util.Iterator
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Returns true if the next token matches the pattern constructed from the
* specified string. The scanner does not advance past any input.
*
* <p> An invocation of this method of the form hasNext(pattern)
* behaves in exactly the same way as the invocation
* <tt>hasNext(Pattern.compile(pattern)).
*
* @param pattern a string specifying the pattern to scan
* @return true if and only if this scanner has another token matching
* the specified pattern
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNext(String pattern) {
return hasNext(patternCache.forName(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.
*
* <p> An invocation of this method of the form next(pattern)
* behaves in exactly the same way as the invocation
* <tt>next(Pattern.compile(pattern)).
*
* @param pattern a string specifying the pattern to scan
* @return the next token
* @throws NoSuchElementException if no such tokens are available
* @throws IllegalStateException if this scanner is closed
*/
public String next(String pattern) {
return next(patternCache.forName(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.
*
* @param pattern the pattern to scan for
* @return true if and only if this scanner has another token matching
* the specified pattern
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNext(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
hasNextPattern = null;
saveState();
while (true) {
if (getCompleteTokenInBuffer(pattern) != null) {
matchValid = true;
cacheResult();
return revertState(true);
}
if (needInput)
readInput();
else
return revertState(false);
}
}
/**
* 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 {@link #hasNext(Pattern)} returned <code>true.
* If the match is successful, the scanner advances past the input that
* matched the pattern.
*
* @param pattern the pattern to scan for
* @return the next token
* @throws NoSuchElementException if no more tokens are available
* @throws IllegalStateException if this scanner is closed
*/
public String next(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
// Did we already find this pattern?
if (hasNextPattern == pattern)
return getCachedResult();
clearCaches();
// Search for the pattern
while (true) {
String token = getCompleteTokenInBuffer(pattern);
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput)
readInput();
else
throwFor();
}
}
/**
* 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.
*
* @return true if and only if this scanner has another line of input
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextLine() {
saveState();
String result = findWithinHorizon(linePattern(), 0);
if (result != null) {
MatchResult mr = this.match();
String lineSep = mr.group(1);
if (lineSep != null) {
result = result.substring(0, result.length() -
lineSep.length());
cacheResult(result);
} else {
cacheResult();
}
}
revertState();
return (result != null);
}
/**
* 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.
*
* <p>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.
*
* @return the line that was skipped
* @throws NoSuchElementException if no line was found
* @throws IllegalStateException if this scanner is closed
*/
public String nextLine() {
if (hasNextPattern == linePattern())
return getCachedResult();
clearCaches();
String result = findWithinHorizon(linePattern, 0);
if (result == null)
throw new NoSuchElementException("No line found");
MatchResult mr = this.match();
String lineSep = mr.group(1);
if (lineSep != null)
result = result.substring(0, result.length() - lineSep.length());
if (result == null)
throw new NoSuchElementException();
else
return result;
}
// Public methods that ignore delimiters
/**
* Attempts to find the next occurrence of a pattern constructed from the
* specified string, ignoring delimiters.
*
* <p>An invocation of this method of the form findInLine(pattern)
* behaves in exactly the same way as the invocation
* <tt>findInLine(Pattern.compile(pattern)).
*
* @param pattern a string specifying the pattern to search for
* @return the text that matched the specified pattern
* @throws IllegalStateException if this scanner is closed
*/
public String findInLine(String pattern) {
return findInLine(patternCache.forName(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 <code>null is returned and the scanner's
* position is unchanged. This method may block waiting for input that
* matches the pattern.
*
* <p>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.
*
* @param pattern the pattern to scan for
* @return the text that matched the specified pattern
* @throws IllegalStateException if this scanner is closed
*/
public String findInLine(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
clearCaches();
// Expand buffer to include the next newline or end of input
int endPosition = 0;
saveState();
while (true) {
String token = findPatternInBuffer(separatorPattern(), 0);
if (token != null) {
endPosition = matcher.start();
break; // up to next newline
}
if (needInput) {
readInput();
} else {
endPosition = buf.limit();
break; // up to end of input
}
}
revertState();
int horizonForLine = endPosition - position;
// If there is nothing between the current pos and the next
// newline simply return null, invoking findWithinHorizon
// with "horizon=0" will scan beyond the line bound.
if (horizonForLine == 0)
return null;
// Search for the pattern
return findWithinHorizon(pattern, horizonForLine);
}
/**
* Attempts to find the next occurrence of a pattern constructed from the
* specified string, ignoring delimiters.
*
* <p>An invocation of this method of the form
* <tt>findWithinHorizon(pattern) behaves in exactly the same way as
* the invocation
* <tt>findWithinHorizon(Pattern.compile(pattern, horizon)).
*
* @param pattern a string specifying the pattern to search for
* @param horizon the search horizon
* @return the text that matched the specified pattern
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if horizon is negative
*/
public String findWithinHorizon(String pattern, int horizon) {
return findWithinHorizon(patternCache.forName(pattern), horizon);
}
/**
* Attempts to find the next occurrence of the specified pattern.
*
* <p>This method searches through the input up to the specified
* search horizon, ignoring delimiters. If the pattern is found the
* scanner advances past the input that matched and returns the string
* that matched the pattern. If no such pattern is detected then the
* null is returned and the scanner's position remains unchanged. This
* method may block waiting for input that matches the pattern.
*
* <p>A scanner will never search more than horizon code
* points beyond its current position. Note that a match may be clipped
* by the horizon; that is, an arbitrary match result may have been
* different if the horizon had been larger. The scanner treats the
* horizon as a transparent, non-anchoring bound (see {@link
* Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}).
*
* <p>If horizon is 0 , then the horizon is ignored and
* this method continues to search through the input looking for the
* specified pattern without bound. In this case it may buffer all of
* the input searching for the pattern.
*
* <p>If horizon is negative, then an IllegalArgumentException is
* thrown.
*
* @param pattern the pattern to scan for
* @param horizon the search horizon
* @return the text that matched the specified pattern
* @throws IllegalStateException if this scanner is closed
* @throws IllegalArgumentException if horizon is negative
*/
public String findWithinHorizon(Pattern pattern, int horizon) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
if (horizon < 0)
throw new IllegalArgumentException("horizon < 0");
clearCaches();
// Search for the pattern
while (true) {
String token = findPatternInBuffer(pattern, horizon);
if (token != null) {
matchValid = true;
return token;
}
if (needInput)
readInput();
else
break; // up to end of input
}
return null;
}
/**
* Skips input that matches the specified pattern, ignoring delimiters.
* This method will skip input if an anchored match of the specified
* pattern succeeds.
*
* <p>If a match to the specified pattern is not found at the
* current position, then no input is skipped and a
* <tt>NoSuchElementException is thrown.
*
* <p>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.
*
* <p>Note that it is possible to skip something without risking a
* <code>NoSuchElementException by using a pattern that can
* match nothing, e.g., <code>sc.skip("[ \t]*").
*
* @param pattern a string specifying the pattern to skip over
* @return this scanner
* @throws NoSuchElementException if the specified pattern is not found
* @throws IllegalStateException if this scanner is closed
*/
public Scanner skip(Pattern pattern) {
ensureOpen();
if (pattern == null)
throw new NullPointerException();
clearCaches();
// Search for the pattern
while (true) {
String token = matchPatternInBuffer(pattern);
if (token != null) {
matchValid = true;
position = matcher.end();
return this;
}
if (needInput)
readInput();
else
throw new NoSuchElementException();
}
}
/**
* Skips input that matches a pattern constructed from the specified
* string.
*
* <p> An invocation of this method of the form skip(pattern)
* behaves in exactly the same way as the invocation
* <tt>skip(Pattern.compile(pattern)).
*
* @param pattern a string specifying the pattern to skip over
* @return this scanner
* @throws IllegalStateException if this scanner is closed
*/
public Scanner skip(String pattern) {
return skip(patternCache.forName(pattern));
}
// Convenience methods for scanning primitives
/**
* 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.
*
* @return true if and only if this scanner's next token is a valid
* boolean value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBoolean() {
return hasNext(boolPattern());
}
/**
* Scans the next token of the input into a boolean value and returns
* that value. This method will throw <code>InputMismatchException
* if the next token cannot be translated into a valid boolean value.
* If the match is successful, the scanner advances past the input that
* matched.
*
* @return the boolean scanned from the input
* @throws InputMismatchException if the next token is not a valid boolean
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public boolean nextBoolean() {
clearCaches();
return Boolean.parseBoolean(next(boolPattern()));
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the default radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* byte value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextByte() {
return hasNextByte(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a byte value in the specified radix using the
* {@link #nextByte} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a byte value
* @return true if and only if this scanner's next token is a valid
* byte value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextByte(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Byte.parseByte(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>byte.
*
* <p> An invocation of this method of the form
* <tt>nextByte() behaves in exactly the same way as the
* invocation <tt>nextByte(radix), where radix
* is the default radix of this scanner.
*
* @return the <tt>byte scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public byte nextByte() {
return nextByte(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>byte.
* This method will throw <code>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.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into a <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Byte#parseByte(String, int) Byte.parseByte} with the
* specified radix.
*
* @param radix the radix used to interpret the token as a byte value
* @return the <tt>byte scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public byte nextByte(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Byte)
&& this.radix == radix) {
byte val = ((Byte)typeCache).byteValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next byte
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Byte.parseByte(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the default radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* short value in the default radix
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextShort() {
return hasNextShort(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a short value in the specified radix using the
* {@link #nextShort} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a short value
* @return true if and only if this scanner's next token is a valid
* short value in the specified radix
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextShort(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Short.parseShort(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>short.
*
* <p> An invocation of this method of the form
* <tt>nextShort() behaves in exactly the same way as the
* invocation <tt>nextShort(radix), where radix
* is the default radix of this scanner.
*
* @return the <tt>short scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public short nextShort() {
return nextShort(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>short.
* This method will throw <code>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.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into a <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Short#parseShort(String, int) Short.parseShort} with the
* specified radix.
*
* @param radix the radix used to interpret the token as a short value
* @return the <tt>short scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public short nextShort(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Short)
&& this.radix == radix) {
short val = ((Short)typeCache).shortValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next short
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Short.parseShort(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the default radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt() {
return hasNextInt(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as an int value in the specified radix using the
* {@link #nextInt} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as an int value
* @return true if and only if this scanner's next token is a valid
* int value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextInt(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* The integer token must be stripped of prefixes, group separators,
* and suffixes, non ascii digits must be converted into ascii digits
* before parse will accept it.
*/
private String processIntegerToken(String token) {
String result = token.replaceAll(""+groupSeparator, "");
boolean isNegative = false;
int preLen = negativePrefix.length();
if ((preLen > 0) && result.startsWith(negativePrefix)) {
isNegative = true;
result = result.substring(preLen);
}
int sufLen = negativeSuffix.length();
if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
isNegative = true;
result = result.substring(result.length() - sufLen,
result.length());
}
if (isNegative)
result = "-" + result;
return result;
}
/**
* Scans the next token of the input as an <tt>int.
*
* <p> An invocation of this method of the form
* <tt>nextInt() behaves in exactly the same way as the
* invocation <tt>nextInt(radix), where radix
* is the default radix of this scanner.
*
* @return the <tt>int scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt() {
return nextInt(defaultRadix);
}
/**
* Scans the next token of the input as an <tt>int.
* This method will throw <code>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.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into an <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Integer#parseInt(String, int) Integer.parseInt} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>int scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a long value in the default radix using the
* {@link #nextLong} method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* long value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextLong() {
return hasNextLong(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a long value in the specified radix using the
* {@link #nextLong} method. The scanner does not advance past any input.
*
* @param radix the radix used to interpret the token as a long value
* @return true if and only if this scanner's next token is a valid
* long value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextLong(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = Long.parseLong(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>long.
*
* <p> An invocation of this method of the form
* <tt>nextLong() behaves in exactly the same way as the
* invocation <tt>nextLong(radix), where radix
* is the default radix of this scanner.
*
* @return the <tt>long scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public long nextLong() {
return nextLong(defaultRadix);
}
/**
* Scans the next token of the input as a <tt>long.
* This method will throw <code>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.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into a <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Long#parseLong(String, int) Long.parseLong} with the
* specified radix.
*
* @param radix the radix used to interpret the token as an int value
* @return the <tt>long scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public long nextLong(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Long)
&& this.radix == radix) {
long val = ((Long)typeCache).longValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Long.parseLong(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* The float token must be stripped of prefixes, group separators,
* and suffixes, non ascii digits must be converted into ascii digits
* before parseFloat will accept it.
*
* If there are non-ascii digits in the token these digits must
* be processed before the token is passed to parseFloat.
*/
private String processFloatToken(String token) {
String result = token.replaceAll(groupSeparator, "");
if (!decimalSeparator.equals("\\."))
result = result.replaceAll(decimalSeparator, ".");
boolean isNegative = false;
int preLen = negativePrefix.length();
if ((preLen > 0) && result.startsWith(negativePrefix)) {
isNegative = true;
result = result.substring(preLen);
}
int sufLen = negativeSuffix.length();
if ((sufLen > 0) && result.endsWith(negativeSuffix)) {
isNegative = true;
result = result.substring(result.length() - sufLen,
result.length());
}
if (result.equals(nanString))
result = "NaN";
if (result.equals(infinityString))
result = "Infinity";
if (isNegative)
result = "-" + result;
// Translate non-ASCII digits
Matcher m = NON_ASCII_DIGIT.matcher(result);
if (m.find()) {
StringBuilder inASCII = new StringBuilder();
for (int i=0; i<result.length(); i++) {
char nextChar = result.charAt(i);
if (Character.isDigit(nextChar)) {
int d = Character.digit(nextChar, 10);
if (d != -1)
inASCII.append(d);
else
inASCII.append(nextChar);
} else {
inASCII.append(nextChar);
}
}
result = inASCII.toString();
}
return result;
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a float value using the {@link #nextFloat}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* float value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextFloat() {
setRadix(10);
boolean result = hasNext(floatPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Float.valueOf(Float.parseFloat(s));
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>float.
* This method will throw <code>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.
*
* <p> If the next token matches the Float regular expression defined above
* then the token is converted into a <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Float#parseFloat Float.parseFloat}. If the token matches
* the localized NaN or infinity strings, then either "Nan" or "Infinity"
* is passed to {@link Float#parseFloat(String) Float.parseFloat} as
* appropriate.
*
* @return the <tt>float scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float
* regular expression, or is out of range
* @throws NoSuchElementException if input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public float nextFloat() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Float)) {
float val = ((Float)typeCache).floatValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
try {
return Float.parseFloat(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a double value using the {@link #nextDouble}
* method. The scanner does not advance past any input.
*
* @return true if and only if this scanner's next token is a valid
* double value
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextDouble() {
setRadix(10);
boolean result = hasNext(floatPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = Double.valueOf(Double.parseDouble(s));
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a <tt>double.
* This method will throw <code>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.
*
* <p> If the next token matches the Float regular expression defined above
* then the token is converted into a <tt>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 {@link Character#digit Character.digit}, prepending a
* negative sign (-) if the locale specific negative prefixes and suffixes
* were present, and passing the resulting string to
* {@link Double#parseDouble Double.parseDouble}. If the token matches
* the localized NaN or infinity strings, then either "Nan" or "Infinity"
* is passed to {@link Double#parseDouble(String) Double.parseDouble} as
* appropriate.
*
* @return the <tt>double scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public double nextDouble() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Double)) {
double val = ((Double)typeCache).doubleValue();
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
return Double.parseDouble(processFloatToken(next(floatPattern())));
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
// Convenience methods for scanning multi precision numbers
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigInteger in the default radix using the
* {@link #nextBigInteger} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* <code>BigInteger
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigInteger() {
return hasNextBigInteger(defaultRadix);
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigInteger in the specified radix using
* the {@link #nextBigInteger} method. The scanner does not advance past
* any input.
*
* @param radix the radix used to interpret the token as an integer
* @return true if and only if this scanner's next token is a valid
* <code>BigInteger
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigInteger(int radix) {
setRadix(radix);
boolean result = hasNext(integerPattern());
if (result) { // Cache it
try {
String s = (matcher.group(SIMPLE_GROUP_INDEX) == null) ?
processIntegerToken(hasNextResult) :
hasNextResult;
typeCache = new BigInteger(s, radix);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a {@link java.math.BigInteger
* BigInteger}.
*
* <p> An invocation of this method of the form
* <tt>nextBigInteger() behaves in exactly the same way as the
* invocation <tt>nextBigInteger(radix), where radix
* is the default radix of this scanner.
*
* @return the <tt>BigInteger scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigInteger nextBigInteger() {
return nextBigInteger(defaultRadix);
}
/**
* Scans the next token of the input as a {@link java.math.BigInteger
* BigInteger}.
*
* <p> If the next token matches the Integer regular expression defined
* above then the token is converted into a <tt>BigInteger value as if
* by removing all group separators, mapping non-ASCII digits into ASCII
* digits via the {@link Character#digit Character.digit}, and passing the
* resulting string to the {@link
* java.math.BigInteger#BigInteger(java.lang.String)
* BigInteger(String, int)} constructor with the specified radix.
*
* @param radix the radix used to interpret the token
* @return the <tt>BigInteger scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigInteger nextBigInteger(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof BigInteger)
&& this.radix == radix) {
BigInteger val = (BigInteger)typeCache;
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return new BigInteger(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Returns true if the next token in this scanner's input can be
* interpreted as a <code>BigDecimal using the
* {@link #nextBigDecimal} method. The scanner does not advance past any
* input.
*
* @return true if and only if this scanner's next token is a valid
* <code>BigDecimal
* @throws IllegalStateException if this scanner is closed
*/
public boolean hasNextBigDecimal() {
setRadix(10);
boolean result = hasNext(decimalPattern());
if (result) { // Cache it
try {
String s = processFloatToken(hasNextResult);
typeCache = new BigDecimal(s);
} catch (NumberFormatException nfe) {
result = false;
}
}
return result;
}
/**
* Scans the next token of the input as a {@link java.math.BigDecimal
* BigDecimal}.
*
* <p> If the next token matches the Decimal regular expression defined
* above then the token is converted into a <tt>BigDecimal value as if
* by removing all group separators, mapping non-ASCII digits into ASCII
* digits via the {@link Character#digit Character.digit}, and passing the
* resulting string to the {@link
* java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)}
* constructor.
*
* @return the <tt>BigDecimal scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Decimal
* regular expression, or is out of range
* @throws NoSuchElementException if the input is exhausted
* @throws IllegalStateException if this scanner is closed
*/
public BigDecimal nextBigDecimal() {
// Check cached result
if ((typeCache != null) && (typeCache instanceof BigDecimal)) {
BigDecimal val = (BigDecimal)typeCache;
useTypeCache();
return val;
}
setRadix(10);
clearCaches();
// Search for next float
try {
String s = processFloatToken(next(decimalPattern()));
return new BigDecimal(s);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}
/**
* Resets this scanner.
*
* <p> Resetting a scanner discards all of its explicit state
* information which may have been changed by invocations of {@link
* #useDelimiter}, {@link #useLocale}, or {@link #useRadix}.
*
* <p> An invocation of this method of the form
* <tt>scanner.reset() behaves in exactly the same way as the
* invocation
*
* <blockquote>{@code * scanner.useDelimiter("\\p{javaWhitespace}+") * .useLocale(Locale.getDefault(Locale.Category.FORMAT)) * .useRadix(10); * }</pre> * * @return this scanner * * @since 1.6 */ public Scanner reset() { delimPattern = WHITESPACE_PATTERN; useLocale(Locale.getDefault(Locale.Category.FORMAT)); useRadix(10); clearCaches(); return this; } } Other Java examples (source code examples)Here is a short list of links related to this Java Scanner.java source code file: |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.