Methods Summary |
---|
private static java.util.regex.Pattern | boolPattern()
Pattern bp = boolPattern;
if (bp == null)
boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN,
Pattern.CASE_INSENSITIVE);
return bp;
|
private void | buildFloatAndDecimalPattern()
// \\p{javaDigit} may not be perfect, see above
String digit = "([0-9]|(\\p{javaDigit}))";
String exponent = "([eE][+-]?"+digit+"+)?";
String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
groupSeparator+digit+digit+digit+")+)";
// Once again digit++ is used for performance, as above
String numeral = "(("+digit+"++)|"+groupedNumeral+")";
String decimalNumeral = "("+numeral+"|"+numeral +
decimalSeparator + digit + "*+|"+ decimalSeparator +
digit + "++)";
String nonNumber = "(NaN|"+nanString+"|Infinity|"+
infinityString+")";
String positiveFloat = "(" + positivePrefix + decimalNumeral +
positiveSuffix + exponent + ")";
String negativeFloat = "(" + negativePrefix + decimalNumeral +
negativeSuffix + exponent + ")";
String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+
positiveFloat + "|" + negativeFloat + ")";
String hexFloat =
"[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?";
String positiveNonNumber = "(" + positivePrefix + nonNumber +
positiveSuffix + ")";
String negativeNonNumber = "(" + negativePrefix + nonNumber +
negativeSuffix + ")";
String signedNonNumber = "(([-+]?"+nonNumber+")|" +
positiveNonNumber + "|" +
negativeNonNumber + ")";
floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" +
signedNonNumber);
decimalPattern = Pattern.compile(decimal);
|
private java.lang.String | buildIntegerPatternString()
String radixDigits = digits.substring(0, radix);
// \\p{javaDigit} is not guaranteed to be appropriate
// here but what can we do? The final authority will be
// whatever parse method is invoked, so ultimately the
// Scanner will do the right thing
String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})";
String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
groupSeparator+digit+digit+digit+")+)";
// digit++ is the possessive form which is necessary for reducing
// backtracking that would otherwise cause unacceptable performance
String numeral = "(("+ digit+"++)|"+groupedNumeral+")";
String javaStyleInteger = "([-+]?(" + numeral + "))";
String negativeInteger = negativePrefix + numeral + negativeSuffix;
String positiveInteger = positivePrefix + numeral + positiveSuffix;
return "("+ javaStyleInteger + ")|(" +
positiveInteger + ")|(" +
negativeInteger + ")";
|
private void | cacheResult()
hasNextResult = matcher.group();
hasNextPosition = matcher.end();
hasNextPattern = matcher.pattern();
|
private void | cacheResult(java.lang.String result)
hasNextResult = result;
hasNextPosition = matcher.end();
hasNextPattern = matcher.pattern();
|
private void | clearCaches()
hasNextPattern = null;
typeCache = null;
|
public void | close()Closes this scanner.
If this scanner has not yet been closed then if its underlying
{@linkplain java.lang.Readable readable} also implements the {@link
java.io.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 {@link IllegalStateException}.
if (closed)
return;
if (source instanceof Closeable) {
try {
((Closeable)source).close();
} catch (IOException ioe) {
lastException = ioe;
}
}
sourceClosed = true;
source = null;
closed = true;
|
private java.util.regex.Pattern | decimalPattern()
if (decimalPattern == null) {
buildFloatAndDecimalPattern();
}
return decimalPattern;
|
public java.util.regex.Pattern | delimiter()Returns the Pattern this Scanner is currently
using to match delimiters.
return delimPattern;
|
private void | ensureOpen()
if (closed)
throw new IllegalStateException("Scanner closed");
|
public java.lang.String | findInLine(java.lang.String pattern)Attempts to find the next occurrence of a pattern constructed from the
specified string, ignoring delimiters.
An invocation of this method of the form findInLine(pattern)
behaves in exactly the same way as the invocation
findInLine(Pattern.compile(pattern)).
return findInLine(patternCache.forName(pattern));
|
public java.lang.String | findInLine(java.util.regex.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.
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);
|
private java.lang.String | findPatternInBuffer(java.util.regex.Pattern pattern, int horizon)
matchValid = false;
matcher.usePattern(pattern);
int bufferLimit = buf.limit();
int horizonLimit = -1;
int searchLimit = bufferLimit;
if (horizon > 0) {
horizonLimit = position + horizon;
if (horizonLimit < bufferLimit)
searchLimit = horizonLimit;
}
matcher.region(position, searchLimit);
if (matcher.find()) {
if (matcher.hitEnd() && (!sourceClosed)) {
// The match may be longer if didn't hit horizon or real end
if (searchLimit != horizonLimit) {
// Hit an artificial end; try to extend the match
needInput = true;
return null;
}
// The match could go away depending on what is next
if ((searchLimit == horizonLimit) && matcher.requireEnd()) {
// Rare case: we hit the end of input and it happens
// that it is at the horizon and the end of input is
// required for the match.
needInput = true;
return null;
}
}
// Did not hit end, or hit real end, or hit horizon
position = matcher.end();
return matcher.group();
}
if (sourceClosed)
return null;
// If there is no specified horizon, or if we have not searched
// to the specified horizon yet, get more input
if ((horizon == 0) || (searchLimit != horizonLimit))
needInput = true;
return null;
|
public java.lang.String | findWithinHorizon(java.lang.String pattern, int horizon)Attempts to find the next occurrence of a pattern constructed from the
specified string, ignoring delimiters.
An invocation of this method of the form
findWithinHorizon(pattern) behaves in exactly the same way as
the invocation
findWithinHorizon(Pattern.compile(pattern, horizon)).
return findWithinHorizon(patternCache.forName(pattern), horizon);
|
public java.lang.String | findWithinHorizon(java.util.regex.Pattern pattern, int horizon)Attempts to find the next occurrence of the specified pattern.
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.
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}).
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.
If horizon is negative, then an IllegalArgumentException is
thrown.
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;
|
private java.util.regex.Pattern | floatPattern()
if (floatPattern == null) {
buildFloatAndDecimalPattern();
}
return floatPattern;
|
private java.lang.String | getCachedResult()
position = hasNextPosition;
hasNextPattern = null;
typeCache = null;
return hasNextResult;
|
private java.lang.String | getCompleteTokenInBuffer(java.util.regex.Pattern pattern)
matchValid = false;
// Skip delims first
matcher.usePattern(delimPattern);
if (!skipped) { // Enforcing only one skip of leading delims
matcher.region(position, buf.limit());
if (matcher.lookingAt()) {
// If more input could extend the delimiters then we must wait
// for more input
if (matcher.hitEnd() && !sourceClosed) {
needInput = true;
return null;
}
// The delims were whole and the matcher should skip them
skipped = true;
position = matcher.end();
}
}
// If we are sitting at the end, no more tokens in buffer
if (position == buf.limit()) {
if (sourceClosed)
return null;
needInput = true;
return null;
}
// Must look for next delims. Simply attempting to match the
// pattern at this point may find a match but it might not be
// the first longest match because of missing input, or it might
// match a partial token instead of the whole thing.
// Then look for next delims
matcher.region(position, buf.limit());
boolean foundNextDelim = matcher.find();
if (foundNextDelim && (matcher.end() == position)) {
// Zero length delimiter match; we should find the next one
// using the automatic advance past a zero length match;
// Otherwise we have just found the same one we just skipped
foundNextDelim = matcher.find();
}
if (foundNextDelim) {
// In the rare case that more input could cause the match
// to be lost and there is more input coming we must wait
// for more input. Note that hitting the end is okay as long
// as the match cannot go away. It is the beginning of the
// next delims we want to be sure about, we don't care if
// they potentially extend further.
if (matcher.requireEnd() && !sourceClosed) {
needInput = true;
return null;
}
int tokenEnd = matcher.start();
// There is a complete token.
if (pattern == null) {
// Must continue with match to provide valid MatchResult
pattern = FIND_ANY_PATTERN;
}
// Attempt to match against the desired pattern
matcher.usePattern(pattern);
matcher.region(position, tokenEnd);
if (matcher.matches()) {
String s = matcher.group();
position = matcher.end();
return s;
} else { // Complete token but it does not match
return null;
}
}
// If we can't find the next delims but no more input is coming,
// then we can treat the remainder as a whole token
if (sourceClosed) {
if (pattern == null) {
// Must continue with match to provide valid MatchResult
pattern = FIND_ANY_PATTERN;
}
// Last token; Match the pattern here or throw
matcher.usePattern(pattern);
matcher.region(position, buf.limit());
if (matcher.matches()) {
String s = matcher.group();
position = matcher.end();
return s;
}
// Last piece does not match
return null;
}
// There is a partial token in the buffer; must read more
// to complete it
needInput = true;
return null;
|
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.
ensureOpen();
saveState();
while (!sourceClosed) {
if (hasTokenInBuffer())
return revertState(true);
readInput();
}
boolean result = hasTokenInBuffer();
return revertState(result);
|
public boolean | hasNext(java.lang.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)).
return hasNext(patternCache.forName(pattern));
|
public boolean | hasNext(java.util.regex.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.
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);
}
|
public boolean | hasNextBigDecimal()Returns true if the next token in this scanner's input can be
interpreted as a BigDecimal using the
{@link #nextBigDecimal} method. The scanner does not advance past any
input.
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;
|
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
{@link #nextBigInteger} method. The scanner does not advance past any
input.
return hasNextBigInteger(defaultRadix);
|
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 {@link #nextBigInteger} method. The scanner does not advance past
any input.
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;
|
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.
return hasNext(boolPattern());
|
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
{@link #nextByte} method. The scanner does not advance past any input.
return hasNextByte(defaultRadix);
|
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
{@link #nextByte} method. The scanner does not advance past any input.
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;
|
public boolean | hasNextDouble()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.
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;
|
public boolean | hasNextFloat()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.
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;
|
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
{@link #nextInt} method. The scanner does not advance past any input.
return hasNextInt(defaultRadix);
|
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
{@link #nextInt} method. The scanner does not advance past any input.
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;
|
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.
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);
|
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
{@link #nextLong} method. The scanner does not advance past any input.
return hasNextLong(defaultRadix);
|
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
{@link #nextLong} method. The scanner does not advance past any input.
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;
|
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
{@link #nextShort} method. The scanner does not advance past any input.
return hasNextShort(defaultRadix);
|
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
{@link #nextShort} method. The scanner does not advance past any input.
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;
|
private boolean | hasTokenInBuffer()
matchValid = false;
matcher.usePattern(delimPattern);
matcher.region(position, buf.limit());
// Skip delims first
if (matcher.lookingAt())
position = matcher.end();
// If we are sitting at the end, no more tokens in buffer
if (position == buf.limit())
return false;
return true;
|
private java.util.regex.Pattern | integerPattern()
if (integerPattern == null) {
integerPattern = patternCache.forName(buildIntegerPatternString());
}
return integerPattern;
|
public java.io.IOException | ioException()Returns the IOException last thrown by this
Scanner 's underlying Readable . This method
returns null if no such exception exists.
return lastException;
|
private static java.util.regex.Pattern | linePattern()
Pattern lp = linePattern;
if (lp == null)
linePattern = lp = Pattern.compile(LINE_PATTERN);
return lp;
|
public java.util.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.
return this.locale;
|
private static java.lang.Readable | makeReadable(java.io.InputStream source, java.lang.String charsetName)
if (source == null)
throw new NullPointerException("source");
InputStreamReader isr = null;
try {
isr = new InputStreamReader(source, charsetName);
} catch (UnsupportedEncodingException uee) {
IllegalArgumentException iae = new IllegalArgumentException();
iae.initCause(uee);
throw iae;
}
return isr;
|
private static java.lang.Readable | makeReadable(java.nio.channels.ReadableByteChannel source)
if (source == null)
throw new NullPointerException("source");
String defaultCharsetName =
java.nio.charset.Charset.defaultCharset().name();
return Channels.newReader(source,
java.nio.charset.Charset.defaultCharset().name());
|
private static java.lang.Readable | makeReadable(java.nio.channels.ReadableByteChannel source, java.lang.String charsetName)
if (source == null)
throw new NullPointerException("source");
if (!Charset.isSupported(charsetName))
throw new IllegalArgumentException(charsetName);
return Channels.newReader(source, charsetName);
|
private boolean | makeSpace()
clearCaches();
int offset = savedScannerPosition == -1 ?
position : savedScannerPosition;
buf.position(offset);
// Gain space by compacting buffer
if (offset > 0) {
buf.compact();
translateSavedIndexes(offset);
position -= offset;
buf.flip();
return true;
}
// Gain space by growing buffer
int newSize = buf.capacity() * 2;
CharBuffer newBuf = CharBuffer.allocate(newSize);
newBuf.put(buf);
newBuf.flip();
translateSavedIndexes(offset);
position -= offset;
buf = newBuf;
matcher.reset(buf);
return true;
|
public java.util.regex.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 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
MatchResult for the search of the
Integer regular expression
defined above. Similarly the {@link #findInLine},
{@link #findWithinHorizon}, and {@link #skip} methods will make a
match available if they succeed.
if (!matchValid)
throw new IllegalStateException("No match result available");
return matcher.toMatchResult();
|
private java.lang.String | matchPatternInBuffer(java.util.regex.Pattern pattern)
matchValid = false;
matcher.usePattern(pattern);
matcher.region(position, buf.limit());
if (matcher.lookingAt()) {
if (matcher.hitEnd() && (!sourceClosed)) {
// Get more input and try again
needInput = true;
return null;
}
position = matcher.end();
return matcher.group();
}
if (sourceClosed)
return null;
// Read more to find pattern
needInput = true;
return null;
|
public java.lang.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 {@link #hasNext} returned
true .
ensureOpen();
clearCaches();
while (true) {
String token = getCompleteTokenInBuffer(null);
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
if (needInput)
readInput();
else
throwFor();
}
|
public java.lang.String | next(java.lang.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)).
return next(patternCache.forName(pattern));
|
public java.lang.String | next(java.util.regex.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 {@link #hasNext(Pattern)} returned true .
If the match is successful, the scanner advances past the input that
matched the 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();
}
|
public java.math.BigDecimal | nextBigDecimal()Scans the next token of the input as a {@link java.math.BigDecimal
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 {@link Character#digit Character.digit}, and passing the
resulting string to the {@link
java.math.BigDecimal#BigDecimal(java.lang.String) BigDecimal(String)}
constructor.
// 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());
}
|
public java.math.BigInteger | nextBigInteger()Scans the next token of the input as a {@link java.math.BigInteger
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.
return nextBigInteger(defaultRadix);
|
public java.math.BigInteger | nextBigInteger(int radix)Scans the next token of the input as a {@link java.math.BigInteger
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 {@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.
// 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());
}
|
public boolean | nextBoolean()Scans the next token of the input into a boolean value and returns
that value. This method will throw 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.
clearCaches();
return Boolean.parseBoolean(next(boolPattern()));
|
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.
return nextByte(defaultRadix);
|
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 {@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.
// 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());
}
|
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 {@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.
// 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());
}
|
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 {@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.
// 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());
}
|
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.
return nextInt(defaultRadix);
|
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 {@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.
// 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());
}
|
public java.lang.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.
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 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.
return nextLong(defaultRadix);
|
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 {@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.
// 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());
}
|
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.
return nextShort(defaultRadix);
|
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 {@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.
// 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());
}
|
private java.lang.String | processFloatToken(java.lang.String token)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.
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;
|
private java.lang.String | processIntegerToken(java.lang.String token)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.
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;
|
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.
return this.defaultRadix;
|
private void | readInput()
if (buf.limit() == buf.capacity())
makeSpace();
// Prepare to receive data
int p = buf.position();
buf.position(buf.limit());
buf.limit(buf.capacity());
int n = 0;
try {
n = source.read(buf);
} catch (IOException ioe) {
lastException = ioe;
n = -1;
}
if (n == -1) {
sourceClosed = true;
needInput = false;
}
if (n > 0)
needInput = false;
// Restore current position and limit for reading
buf.limit(buf.position());
buf.position(p);
|
public void | remove()The remove operation is not supported by this implementation of
Iterator .
throw new UnsupportedOperationException();
|
public java.util.Scanner | reset()Resets this scanner.
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}.
An invocation of this method of the form
scanner.reset() behaves in exactly the same way as the
invocation
scanner.useDelimiter("\\p{javaWhitespace}+")
.useLocale(Locale.getDefault())
.useRadix(10);
delimPattern = WHITESPACE_PATTERN;
useLocale(Locale.getDefault());
useRadix(10);
clearCaches();
return this;
|
private void | revertState()
this.position = savedScannerPosition;
savedScannerPosition = -1;
skipped = false;
|
private boolean | revertState(boolean b)
this.position = savedScannerPosition;
savedScannerPosition = -1;
skipped = false;
return b;
|
private void | saveState()
savedScannerPosition = position;
|
private static java.util.regex.Pattern | separatorPattern()
Pattern sp = separatorPattern;
if (sp == null)
separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN);
return sp;
|
private void | setRadix(int radix)
if (this.radix != radix) {
// Force rebuilding and recompilation of radix dependent patterns
integerPattern = null;
this.radix = radix;
}
|
public java.util.Scanner | skip(java.util.regex.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]*") .
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();
}
|
public java.util.Scanner | skip(java.lang.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)).
return skip(patternCache.forName(pattern));
|
private void | throwFor()
skipped = false;
if ((sourceClosed) && (position == buf.limit()))
throw new NoSuchElementException();
else
throw new InputMismatchException();
|
public java.lang.String | toString()Returns the string representation of this Scanner . The
string representation of a Scanner contains information
that may be useful for debugging. The exact format is unspecified.
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();
|
private void | translateSavedIndexes(int offset)
if (savedScannerPosition != -1)
savedScannerPosition -= offset;
|
public java.util.Scanner | useDelimiter(java.util.regex.Pattern pattern)Sets this scanner's delimiting pattern to the specified pattern.
delimPattern = pattern;
return this;
|
public java.util.Scanner | useDelimiter(java.lang.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 {@link #reset} method will set the scanner's delimiter
to the default.
delimPattern = patternCache.forName(pattern);
return this;
|
public java.util.Scanner | useLocale(java.util.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 {@link #reset} method will set the scanner's locale to
the initial 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;
|
public java.util.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 {@link #reset} method will set the scanner's radix to
10 .
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;
|
private void | useTypeCache()
if (closed)
throw new IllegalStateException("Scanner closed");
position = hasNextPosition;
hasNextPattern = null;
typeCache = null;
|