Scanner.java revision 2700
1008N/A/*
1008N/A * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
1008N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1008N/A *
1008N/A * This code is free software; you can redistribute it and/or modify it
1008N/A * under the terms of the GNU General Public License version 2 only, as
1008N/A * published by the Free Software Foundation. Oracle designates this
1008N/A * particular file as subject to the "Classpath" exception as provided
1008N/A * by Oracle in the LICENSE file that accompanied this code.
1008N/A *
1008N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1008N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1008N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1008N/A * version 2 for more details (a copy is included in the LICENSE file that
1008N/A * accompanied this code).
1008N/A *
1008N/A * You should have received a copy of the GNU General Public License version
1008N/A * 2 along with this work; if not, write to the Free Software Foundation,
1008N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1008N/A *
1008N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1008N/A * or visit www.oracle.com if you need additional information or have any
1008N/A * questions.
1008N/A */
1008N/A
1008N/Apackage java.util;
1008N/A
1008N/Aimport java.nio.file.FileRef;
1008N/Aimport java.util.regex.*;
1008N/Aimport java.io.*;
1008N/Aimport java.math.*;
1008N/Aimport java.nio.*;
1008N/Aimport java.nio.channels.*;
1008N/Aimport java.nio.charset.*;
1008N/Aimport java.text.*;
1008N/Aimport java.util.Locale;
1008N/Aimport sun.misc.LRUCache;
1008N/A
1008N/A/**
1008N/A * A simple text scanner which can parse primitive types and strings using
1008N/A * regular expressions.
1008N/A *
1008N/A * <p>A <code>Scanner</code> breaks its input into tokens using a
1008N/A * delimiter pattern, which by default matches whitespace. The resulting
1008N/A * tokens may then be converted into values of different types using the
1008N/A * various <tt>next</tt> methods.
1008N/A *
1008N/A * <p>For example, this code allows a user to read a number from
1008N/A * <tt>System.in</tt>:
1008N/A * <blockquote><pre>
1008N/A * Scanner sc = new Scanner(System.in);
1008N/A * int i = sc.nextInt();
1008N/A * </pre></blockquote>
1008N/A *
1008N/A * <p>As another example, this code allows <code>long</code> types to be
1008N/A * assigned from entries in a file <code>myNumbers</code>:
1008N/A * <blockquote><pre>
1008N/A * Scanner sc = new Scanner(new File("myNumbers"));
1008N/A * while (sc.hasNextLong()) {
1008N/A * long aLong = sc.nextLong();
1008N/A * }</pre></blockquote>
1008N/A *
1008N/A * <p>The scanner can also use delimiters other than whitespace. This
1008N/A * example reads several items in from a string:
1008N/A *<blockquote><pre>
1008N/A * String input = "1 fish 2 fish red fish blue fish";
1008N/A * Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
1008N/A * System.out.println(s.nextInt());
1008N/A * System.out.println(s.nextInt());
1008N/A * System.out.println(s.next());
1008N/A * System.out.println(s.next());
1008N/A * s.close(); </pre></blockquote>
1008N/A * <p>
1008N/A * prints the following output:
1008N/A * <blockquote><pre>
1008N/A * 1
1008N/A * 2
1548N/A * red
1548N/A * blue </pre></blockquote>
1548N/A *
1548N/A * <p>The same output can be generated with this code, which uses a regular
1548N/A * expression to parse all four tokens at once:
1548N/A *<blockquote><pre>
1548N/A * String input = "1 fish 2 fish red fish blue fish";
1548N/A * Scanner s = new Scanner(input);
1548N/A * s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
1548N/A * MatchResult result = s.match();
1548N/A * for (int i=1; i<=result.groupCount(); i++)
1548N/A * System.out.println(result.group(i));
1548N/A * s.close(); </pre></blockquote>
1548N/A *
1548N/A * <p>The <a name="default-delimiter">default whitespace delimiter</a> used
1548N/A * by a scanner is as recognized by {@link java.lang.Character}.{@link
1548N/A * java.lang.Character#isWhitespace(char) isWhitespace}. The {@link #reset}
1548N/A * method will reset the value of the scanner's delimiter to the default
1548N/A * whitespace delimiter regardless of whether it was previously changed.
1548N/A *
1548N/A * <p>A scanning operation may block waiting for input.
1548N/A *
1548N/A * <p>The {@link #next} and {@link #hasNext} methods and their
1548N/A * primitive-type companion methods (such as {@link #nextInt} and
1548N/A * {@link #hasNextInt}) first skip any input that matches the delimiter
1008N/A * pattern, and then attempt to return the next token. Both <tt>hasNext</tt>
1008N/A * and <tt>next</tt> methods may block waiting for further input. Whether a
1008N/A * <tt>hasNext</tt> method blocks has no connection to whether or not its
1008N/A * associated <tt>next</tt> method will block.
1008N/A *
1008N/A * <p> The {@link #findInLine}, {@link #findWithinHorizon}, and {@link #skip}
1008N/A * methods operate independently of the delimiter pattern. These methods will
1008N/A * attempt to match the specified pattern with no regard to delimiters in the
1008N/A * input and thus can be used in special circumstances where delimiters are
1008N/A * not relevant. These methods may block waiting for more input.
1008N/A *
1008N/A * <p>When a scanner throws an {@link InputMismatchException}, the scanner
1008N/A * will not pass the token that caused the exception, so that it may be
1008N/A * retrieved or skipped via some other method.
1008N/A *
1008N/A * <p>Depending upon the type of delimiting pattern, empty tokens may be
1008N/A * returned. For example, the pattern <tt>"\\s+"</tt> will return no empty
1008N/A * tokens since it matches multiple instances of the delimiter. The delimiting
1008N/A * pattern <tt>"\\s"</tt> could return empty tokens since it only passes one
1008N/A * space at a time.
1008N/A *
1008N/A * <p> A scanner can read text from any object which implements the {@link
1008N/A * java.lang.Readable} interface. If an invocation of the underlying
1008N/A * readable's {@link java.lang.Readable#read} method throws an {@link
1008N/A * java.io.IOException} then the scanner assumes that the end of the input
1008N/A * has been reached. The most recent <tt>IOException</tt> thrown by the
1008N/A * underlying readable can be retrieved via the {@link #ioException} method.
1008N/A *
1008N/A * <p>When a <code>Scanner</code> is closed, it will close its input source
1008N/A * if the source implements the {@link java.io.Closeable} interface.
1008N/A *
1008N/A * <p>A <code>Scanner</code> is not safe for multithreaded use without
1008N/A * external synchronization.
1008N/A *
1008N/A * <p>Unless otherwise mentioned, passing a <code>null</code> parameter into
1008N/A * any method of a <code>Scanner</code> will cause a
1008N/A * <code>NullPointerException</code> to be thrown.
1008N/A *
1008N/A * <p>A scanner will default to interpreting numbers as decimal unless a
1008N/A * different radix has been set by using the {@link #useRadix} method. The
1426N/A * {@link #reset} method will reset the value of the scanner's radix to
1426N/A * <code>10</code> regardless of whether it was previously changed.
1426N/A *
1426N/A * <a name="localized-numbers">
1426N/A * <h4> Localized numbers </h4>
1426N/A *
1426N/A * <p> An instance of this class is capable of scanning numbers in the standard
1426N/A * formats as well as in the formats of the scanner's locale. A scanner's
1426N/A * <a name="initial-locale">initial locale </a>is the value returned by the {@link
1426N/A * java.util.Locale#getDefault} method; it may be changed via the {@link
1426N/A * #useLocale} method. The {@link #reset} method will reset the value of the
1426N/A * scanner's locale to the initial locale regardless of whether it was
1426N/A * previously changed.
1426N/A *
1426N/A * <p>The localized formats are defined in terms of the following parameters,
1008N/A * which for a particular locale are taken from that locale's {@link
1008N/A * java.text.DecimalFormat DecimalFormat} object, <tt>df</tt>, and its and
1008N/A * {@link java.text.DecimalFormatSymbols DecimalFormatSymbols} object,
1008N/A * <tt>dfs</tt>.
1008N/A *
1008N/A * <blockquote><table>
1008N/A * <tr><td valign="top"><i>LocalGroupSeparator&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The character used to separate thousands groups,
1008N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
1008N/A * java.text.DecimalFormatSymbols#getGroupingSeparator
1008N/A * getGroupingSeparator()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalDecimalSeparator&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The character used for the decimal point,
1008N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
1008N/A * java.text.DecimalFormatSymbols#getDecimalSeparator
1008N/A * getDecimalSeparator()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalPositivePrefix&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that appears before a positive number (may
1008N/A * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
1008N/A * java.text.DecimalFormat#getPositivePrefix
1008N/A * getPositivePrefix()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalPositiveSuffix&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that appears after a positive number (may be
1008N/A * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
1008N/A * java.text.DecimalFormat#getPositiveSuffix
1008N/A * getPositiveSuffix()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalNegativePrefix&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that appears before a negative number (may
1008N/A * be empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
1008N/A * java.text.DecimalFormat#getNegativePrefix
1008N/A * getNegativePrefix()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalNegativeSuffix&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that appears after a negative number (may be
1008N/A * empty), <i>i.e.,</i>&nbsp;<tt>df.</tt>{@link
1008N/A * java.text.DecimalFormat#getNegativeSuffix
1008N/A * getNegativeSuffix()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalNaN&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that represents not-a-number for
1008N/A * floating-point values,
1008N/A * <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
1008N/A * java.text.DecimalFormatSymbols#getNaN
1008N/A * getNaN()}</td></tr>
1008N/A * <tr><td valign="top"><i>LocalInfinity&nbsp;&nbsp;</i></td>
1008N/A * <td valign="top">The string that represents infinity for floating-point
1008N/A * values, <i>i.e.,</i>&nbsp;<tt>dfs.</tt>{@link
1008N/A * java.text.DecimalFormatSymbols#getInfinity
1008N/A * getInfinity()}</td></tr>
1008N/A * </table></blockquote>
1008N/A *
1008N/A * <a name="number-syntax">
1008N/A * <h4> Number syntax </h4>
1008N/A *
1008N/A * <p> The strings that can be parsed as numbers by an instance of this class
1008N/A * are specified in terms of the following regular-expression grammar, where
1008N/A * Rmax is the highest digit in the radix being used (for example, Rmax is 9
1008N/A * in base 10).
1008N/A *
1008N/A * <p>
1008N/A * <table cellspacing=0 cellpadding=0 align=center>
1008N/A *
1008N/A * <tr><td valign=top align=right><i>NonASCIIDigit</i>&nbsp;&nbsp;::</td>
1008N/A * <td valign=top>= A non-ASCII character c for which
1008N/A * {@link java.lang.Character#isDigit Character.isDigit}<tt>(c)</tt>
1008N/A * returns&nbsp;true</td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>Non0Digit</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= [1-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>Digit</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= [0-</tt><i>Rmax</i><tt>] | </tt><i>NonASCIIDigit</i></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td valign=top align=right><i>GroupedNumeral</i>&nbsp;&nbsp;::</td>
1008N/A * <td valign=top>
1008N/A * <table cellpadding=0 cellspacing=0>
1008N/A * <tr><td><tt>= (&nbsp;</tt></td>
1008N/A * <td><i>Non0Digit</i><tt>
1008N/A * </tt><i>Digit</i><tt>?
1008N/A * </tt><i>Digit</i><tt>?</tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>(&nbsp;</tt><i>LocalGroupSeparator</i><tt>
1008N/A * </tt><i>Digit</i><tt>
1008N/A * </tt><i>Digit</i><tt>
1008N/A * </tt><i>Digit</i><tt> )+ )</tt></td></tr>
1008N/A * </table></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>Numeral</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= ( ( </tt><i>Digit</i><tt>+ )
1008N/A * | </tt><i>GroupedNumeral</i><tt> )</tt></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td valign=top align=right>
1008N/A * <a name="Integer-regex"><i>Integer</i>&nbsp;&nbsp;::</td>
1008N/A * <td valign=top><tt>= ( [-+]? ( </tt><i>Numeral</i><tt>
1008N/A * ) )</tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt> </tt><i>Numeral</i><tt>
1008N/A * </tt><i>LocalPositiveSuffix</i></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt> </tt><i>Numeral</i><tt>
1008N/A * </tt><i>LocalNegativeSuffix</i></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>DecimalNumeral</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= </tt><i>Numeral</i></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>Numeral</i><tt>
1008N/A * </tt><i>LocalDecimalSeparator</i><tt>
1008N/A * </tt><i>Digit</i><tt>*</tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalDecimalSeparator</i><tt>
1008N/A * </tt><i>Digit</i><tt>+</tt></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>Exponent</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= ( [eE] [+-]? </tt><i>Digit</i><tt>+ )</tt></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right>
1008N/A * <a name="Decimal-regex"><i>Decimal</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= ( [-+]? </tt><i>DecimalNumeral</i><tt>
1008N/A * </tt><i>Exponent</i><tt>? )</tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
1008N/A * </tt><i>DecimalNumeral</i><tt>
1008N/A * </tt><i>LocalPositiveSuffix</i>
1008N/A * </tt><i>Exponent</i><tt>?</td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
1008N/A * </tt><i>DecimalNumeral</i><tt>
1008N/A * </tt><i>LocalNegativeSuffix</i>
1008N/A * </tt><i>Exponent</i><tt>?</td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>HexFloat</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= [-+]? 0[xX][0-9a-fA-F]*\.[0-9a-fA-F]+
1008N/A * ([pP][-+]?[0-9]+)?</tt></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>NonNumber</i>&nbsp;&nbsp;::</td>
1008N/A * <td valign=top><tt>= NaN
1008N/A * | </tt><i>LocalNan</i><tt>
1008N/A * | Infinity
1008N/A * | </tt><i>LocalInfinity</i></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td align=right><i>SignedNonNumber</i>&nbsp;&nbsp;::</td>
1008N/A * <td><tt>= ( [-+]? </tt><i>NonNumber</i><tt> )</tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalPositivePrefix</i><tt>
1008N/A * </tt><i>NonNumber</i><tt>
1008N/A * </tt><i>LocalPositiveSuffix</i></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>LocalNegativePrefix</i><tt>
1008N/A * </tt><i>NonNumber</i><tt>
1008N/A * </tt><i>LocalNegativeSuffix</i></td></tr>
1008N/A *
1008N/A * <tr><td>&nbsp;</td></tr>
1008N/A *
1008N/A * <tr><td valign=top align=right>
1008N/A * <a name="Float-regex"><i>Float</i>&nbsp;&nbsp;::</td>
1008N/A * <td valign=top><tt>= </tt><i>Decimal</i><tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>HexFloat</i><tt></td></tr>
1008N/A * <tr><td></td>
1008N/A * <td><tt>| </tt><i>SignedNonNumber</i><tt></td></tr>
1008N/A *
1008N/A * </table>
1008N/A * </center>
1008N/A *
1008N/A * <p> Whitespace is not significant in the above regular expressions.
1008N/A *
1008N/A * @since 1.5
1008N/A */
1008N/Apublic final class Scanner implements Iterator<String>, Closeable {
1008N/A
1008N/A // Internal buffer used to hold input
1008N/A private CharBuffer buf;
1008N/A
1418N/A // Size of internal character buffer
1418N/A private static final int BUFFER_SIZE = 1024; // change to 1024;
1418N/A
1418N/A // The index into the buffer currently held by the Scanner
1418N/A private int position;
1418N/A
1418N/A // Internal matcher used for finding delimiters
1418N/A private Matcher matcher;
1418N/A
1418N/A // Pattern used to delimit tokens
1418N/A private Pattern delimPattern;
1418N/A
1418N/A // Pattern found in last hasNext operation
1418N/A private Pattern hasNextPattern;
1418N/A
1418N/A // Position after last hasNext operation
1418N/A private int hasNextPosition;
1008N/A
1008N/A // Result after last hasNext operation
1008N/A private String hasNextResult;
1008N/A
1008N/A // The input source
1008N/A private Readable source;
1008N/A
1008N/A // Boolean is true if source is done
1008N/A private boolean sourceClosed = false;
1008N/A
1008N/A // Boolean indicating more input is required
1008N/A private boolean needInput = false;
1008N/A
1008N/A // Boolean indicating if a delim has been skipped this operation
1008N/A private boolean skipped = false;
1008N/A
1008N/A // A store of a position that the scanner may fall back to
1008N/A private int savedScannerPosition = -1;
1008N/A
1008N/A // A cache of the last primitive type scanned
1008N/A private Object typeCache = null;
1008N/A
1008N/A // Boolean indicating if a match result is available
1008N/A private boolean matchValid = false;
1008N/A
1008N/A // Boolean indicating if this scanner has been closed
1008N/A private boolean closed = false;
1008N/A
1008N/A // The current radix used by this scanner
1008N/A private int radix = 10;
1008N/A
1008N/A // The default radix for this scanner
1008N/A private int defaultRadix = 10;
1008N/A
1008N/A // The locale used by this scanner
1008N/A private Locale locale = null;
1008N/A
1008N/A // A cache of the last few recently used Patterns
1008N/A private LRUCache<String,Pattern> patternCache =
1008N/A new LRUCache<String,Pattern>(7) {
1008N/A protected Pattern create(String s) {
1008N/A return Pattern.compile(s);
1008N/A }
1008N/A protected boolean hasName(Pattern p, String s) {
1008N/A return p.pattern().equals(s);
1008N/A }
1008N/A };
1008N/A
1008N/A // A holder of the last IOException encountered
1008N/A private IOException lastException;
1008N/A
1008N/A // A pattern for java whitespace
1008N/A private static Pattern WHITESPACE_PATTERN = Pattern.compile(
1008N/A "\\p{javaWhitespace}+");
1008N/A
1008N/A // A pattern for any token
1008N/A private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*");
1008N/A
1008N/A // A pattern for non-ASCII digits
1008N/A private static Pattern NON_ASCII_DIGIT = Pattern.compile(
1008N/A "[\\p{javaDigit}&&[^0-9]]");
1008N/A
1008N/A // Fields and methods to support scanning primitive types
1008N/A
1008N/A /**
1008N/A * Locale dependent values used to scan numbers
1008N/A */
1008N/A private String groupSeparator = "\\,";
1008N/A private String decimalSeparator = "\\.";
1008N/A private String nanString = "NaN";
1008N/A private String infinityString = "Infinity";
1008N/A private String positivePrefix = "";
1008N/A private String negativePrefix = "\\-";
1008N/A private String positiveSuffix = "";
1008N/A private String negativeSuffix = "";
1008N/A
1008N/A /**
1008N/A * Fields and an accessor method to match booleans
1008N/A */
1008N/A private static volatile Pattern boolPattern;
1008N/A private static final String BOOLEAN_PATTERN = "true|false";
1008N/A private static Pattern boolPattern() {
1426N/A Pattern bp = boolPattern;
1426N/A if (bp == null)
1426N/A boolPattern = bp = Pattern.compile(BOOLEAN_PATTERN,
1426N/A Pattern.CASE_INSENSITIVE);
1426N/A return bp;
1426N/A }
1426N/A
1426N/A /**
1426N/A * Fields and methods to match bytes, shorts, ints, and longs
1426N/A */
1426N/A private Pattern integerPattern;
1426N/A private String digits = "0123456789abcdefghijklmnopqrstuvwxyz";
1426N/A private String non0Digit = "[\\p{javaDigit}&&[^0]]";
1426N/A private int SIMPLE_GROUP_INDEX = 5;
1426N/A private String buildIntegerPatternString() {
1426N/A String radixDigits = digits.substring(0, radix);
1426N/A // \\p{javaDigit} is not guaranteed to be appropriate
1426N/A // here but what can we do? The final authority will be
1426N/A // whatever parse method is invoked, so ultimately the
1426N/A // Scanner will do the right thing
1426N/A String digit = "((?i)["+radixDigits+"]|\\p{javaDigit})";
1426N/A String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
1426N/A groupSeparator+digit+digit+digit+")+)";
1426N/A // digit++ is the possessive form which is necessary for reducing
1426N/A // backtracking that would otherwise cause unacceptable performance
1426N/A String numeral = "(("+ digit+"++)|"+groupedNumeral+")";
1426N/A String javaStyleInteger = "([-+]?(" + numeral + "))";
1426N/A String negativeInteger = negativePrefix + numeral + negativeSuffix;
1426N/A String positiveInteger = positivePrefix + numeral + positiveSuffix;
1426N/A return "("+ javaStyleInteger + ")|(" +
1426N/A positiveInteger + ")|(" +
1426N/A negativeInteger + ")";
1426N/A }
1426N/A private Pattern integerPattern() {
1426N/A if (integerPattern == null) {
1426N/A integerPattern = patternCache.forName(buildIntegerPatternString());
1426N/A }
1426N/A return integerPattern;
1426N/A }
1426N/A
1426N/A /**
1426N/A * Fields and an accessor method to match line separators
1426N/A */
1426N/A private static volatile Pattern separatorPattern;
1426N/A private static volatile Pattern linePattern;
1426N/A private static final String LINE_SEPARATOR_PATTERN =
1426N/A "\r\n|[\n\r\u2028\u2029\u0085]";
1426N/A private static final String LINE_PATTERN = ".*("+LINE_SEPARATOR_PATTERN+")|.+$";
1426N/A
1426N/A private static Pattern separatorPattern() {
1426N/A Pattern sp = separatorPattern;
1426N/A if (sp == null)
1008N/A separatorPattern = sp = Pattern.compile(LINE_SEPARATOR_PATTERN);
1008N/A return sp;
1008N/A }
1008N/A
1008N/A private static Pattern linePattern() {
1008N/A Pattern lp = linePattern;
1008N/A if (lp == null)
1008N/A linePattern = lp = Pattern.compile(LINE_PATTERN);
1008N/A return lp;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Fields and methods to match floats and doubles
1008N/A */
1008N/A private Pattern floatPattern;
1008N/A private Pattern decimalPattern;
1008N/A private void buildFloatAndDecimalPattern() {
1008N/A // \\p{javaDigit} may not be perfect, see above
1008N/A String digit = "([0-9]|(\\p{javaDigit}))";
1008N/A String exponent = "([eE][+-]?"+digit+"+)?";
1008N/A String groupedNumeral = "("+non0Digit+digit+"?"+digit+"?("+
1008N/A groupSeparator+digit+digit+digit+")+)";
1008N/A // Once again digit++ is used for performance, as above
1008N/A String numeral = "(("+digit+"++)|"+groupedNumeral+")";
1008N/A String decimalNumeral = "("+numeral+"|"+numeral +
1008N/A decimalSeparator + digit + "*+|"+ decimalSeparator +
1008N/A digit + "++)";
1008N/A String nonNumber = "(NaN|"+nanString+"|Infinity|"+
1008N/A infinityString+")";
1008N/A String positiveFloat = "(" + positivePrefix + decimalNumeral +
1008N/A positiveSuffix + exponent + ")";
1008N/A String negativeFloat = "(" + negativePrefix + decimalNumeral +
1008N/A negativeSuffix + exponent + ")";
1008N/A String decimal = "(([-+]?" + decimalNumeral + exponent + ")|"+
1008N/A positiveFloat + "|" + negativeFloat + ")";
1008N/A String hexFloat =
1008N/A "[-+]?0[xX][0-9a-fA-F]*\\.[0-9a-fA-F]+([pP][-+]?[0-9]+)?";
1008N/A String positiveNonNumber = "(" + positivePrefix + nonNumber +
1008N/A positiveSuffix + ")";
1008N/A String negativeNonNumber = "(" + negativePrefix + nonNumber +
1008N/A negativeSuffix + ")";
1008N/A String signedNonNumber = "(([-+]?"+nonNumber+")|" +
1008N/A positiveNonNumber + "|" +
1008N/A negativeNonNumber + ")";
1008N/A floatPattern = Pattern.compile(decimal + "|" + hexFloat + "|" +
1008N/A signedNonNumber);
1008N/A decimalPattern = Pattern.compile(decimal);
1008N/A }
1008N/A private Pattern floatPattern() {
1008N/A if (floatPattern == null) {
1008N/A buildFloatAndDecimalPattern();
1008N/A }
1008N/A return floatPattern;
1008N/A }
1008N/A private Pattern decimalPattern() {
1008N/A if (decimalPattern == null) {
1008N/A buildFloatAndDecimalPattern();
1008N/A }
1008N/A return decimalPattern;
1008N/A }
1008N/A
1008N/A // Constructors
1008N/A
1008N/A /**
1008N/A * Constructs a <code>Scanner</code> that returns values scanned
1008N/A * from the specified source delimited by the specified pattern.
1008N/A *
1008N/A * @param source A character source implementing the Readable interface
1008N/A * @param pattern A delimiting pattern
1008N/A * @return A scanner with the specified source and pattern
1008N/A */
1008N/A private Scanner(Readable source, Pattern pattern) {
1008N/A if (source == null)
1008N/A throw new NullPointerException("source");
1008N/A if (pattern == null)
1008N/A throw new NullPointerException("pattern");
1008N/A this.source = source;
1008N/A delimPattern = pattern;
1008N/A buf = CharBuffer.allocate(BUFFER_SIZE);
1008N/A buf.limit(0);
1008N/A matcher = delimPattern.matcher(buf);
1008N/A matcher.useTransparentBounds(true);
1008N/A matcher.useAnchoringBounds(false);
1008N/A useLocale(Locale.getDefault(Locale.Category.FORMAT));
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified source.
1008N/A *
1008N/A * @param source A character source implementing the {@link Readable}
1008N/A * interface
1008N/A */
1008N/A public Scanner(Readable source) {
1008N/A this(source, WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified input stream. Bytes from the stream are converted
1008N/A * into characters using the underlying platform's
1008N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
1008N/A *
1008N/A * @param source An input stream to be scanned
1008N/A */
1008N/A public Scanner(InputStream source) {
1008N/A this(new InputStreamReader(source), WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified input stream. Bytes from the stream are converted
1008N/A * into characters using the specified charset.
1008N/A *
1008N/A * @param source An input stream to be scanned
1008N/A * @param charsetName The encoding type used to convert bytes from the
1008N/A * stream into characters to be scanned
1008N/A * @throws IllegalArgumentException if the specified character set
1008N/A * does not exist
1008N/A */
1008N/A public Scanner(InputStream source, String charsetName) {
1008N/A this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A private static Readable makeReadable(InputStream source,
1008N/A String charsetName)
1008N/A {
1008N/A if (source == null)
1008N/A throw new NullPointerException("source");
1008N/A InputStreamReader isr = null;
1008N/A try {
1008N/A isr = new InputStreamReader(source, charsetName);
1008N/A } catch (UnsupportedEncodingException uee) {
1008N/A IllegalArgumentException iae = new IllegalArgumentException();
1008N/A iae.initCause(uee);
1008N/A throw iae;
1008N/A }
1008N/A return isr;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified file. Bytes from the file are converted into
1008N/A * characters using the underlying platform's
1008N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
1008N/A *
1008N/A * @param source A file to be scanned
1008N/A * @throws FileNotFoundException if source is not found
1008N/A */
1008N/A public Scanner(File source)
1008N/A throws FileNotFoundException
1008N/A {
1008N/A this((ReadableByteChannel)(new FileInputStream(source).getChannel()));
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified file. Bytes from the file are converted into
1008N/A * characters using the specified charset.
1008N/A *
1008N/A * @param source A file to be scanned
1008N/A * @param charsetName The encoding type used to convert bytes from the file
1008N/A * into characters to be scanned
1008N/A * @throws FileNotFoundException if source is not found
1008N/A * @throws IllegalArgumentException if the specified encoding is
1008N/A * not found
1008N/A */
1008N/A public Scanner(File source, String charsetName)
1008N/A throws FileNotFoundException
1008N/A {
1008N/A this((ReadableByteChannel)(new FileInputStream(source).getChannel()),
1008N/A charsetName);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified file. Bytes from the file are converted into
1008N/A * characters using the underlying platform's
1008N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
1008N/A *
1008N/A * @param source
1008N/A * A file to be scanned
1008N/A * @throws IOException
1008N/A * if an I/O error occurs opening source
1008N/A *
1008N/A * @since 1.7
1008N/A */
1008N/A public Scanner(FileRef source)
1008N/A throws IOException
1008N/A {
1008N/A this(source.newInputStream());
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified file. Bytes from the file are converted into
1008N/A * characters using the specified charset.
1008N/A *
1008N/A * @param source
1008N/A * A file to be scanned
1008N/A * @param charsetName
1008N/A * The encoding type used to convert bytes from the file
1008N/A * into characters to be scanned
1008N/A * @throws IOException
1008N/A * if an I/O error occurs opening source
1008N/A * @throws IllegalArgumentException
1008N/A * if the specified encoding is not found
1008N/A * @since 1.7
1008N/A */
1008N/A public Scanner(FileRef source, String charsetName)
1008N/A throws IOException
1008N/A {
1008N/A this(source.newInputStream(), charsetName);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified string.
1008N/A *
1008N/A * @param source A string to scan
1008N/A */
1008N/A public Scanner(String source) {
1008N/A this(new StringReader(source), WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified channel. Bytes from the source are converted into
1008N/A * characters using the underlying platform's
1008N/A * {@linkplain java.nio.charset.Charset#defaultCharset() default charset}.
1008N/A *
1008N/A * @param source A channel to scan
1008N/A */
1008N/A public Scanner(ReadableByteChannel source) {
1008N/A this(makeReadable(source), WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A private static Readable makeReadable(ReadableByteChannel source) {
1008N/A if (source == null)
1008N/A throw new NullPointerException("source");
1008N/A String defaultCharsetName =
1008N/A java.nio.charset.Charset.defaultCharset().name();
1008N/A return Channels.newReader(source,
1008N/A java.nio.charset.Charset.defaultCharset().name());
1008N/A }
1008N/A
1008N/A /**
1008N/A * Constructs a new <code>Scanner</code> that produces values scanned
1008N/A * from the specified channel. Bytes from the source are converted into
1008N/A * characters using the specified charset.
1008N/A *
1008N/A * @param source A channel to scan
1008N/A * @param charsetName The encoding type used to convert bytes from the
1008N/A * channel into characters to be scanned
1008N/A * @throws IllegalArgumentException if the specified character set
1008N/A * does not exist
1008N/A */
1008N/A public Scanner(ReadableByteChannel source, String charsetName) {
1008N/A this(makeReadable(source, charsetName), WHITESPACE_PATTERN);
1008N/A }
1008N/A
1008N/A private static Readable makeReadable(ReadableByteChannel source,
1008N/A String charsetName)
1008N/A {
1008N/A if (source == null)
1008N/A throw new NullPointerException("source");
1008N/A if (!Charset.isSupported(charsetName))
1008N/A throw new IllegalArgumentException(charsetName);
1008N/A return Channels.newReader(source, charsetName);
1008N/A }
1008N/A
1008N/A // Private primitives used to support scanning
1008N/A
1008N/A private void saveState() {
1008N/A savedScannerPosition = position;
1008N/A }
1008N/A
1008N/A private void revertState() {
1008N/A this.position = savedScannerPosition;
1008N/A savedScannerPosition = -1;
1008N/A skipped = false;
1008N/A }
1008N/A
1008N/A private boolean revertState(boolean b) {
1008N/A this.position = savedScannerPosition;
1008N/A savedScannerPosition = -1;
1008N/A skipped = false;
1008N/A return b;
1008N/A }
1008N/A
1008N/A private void cacheResult() {
1008N/A hasNextResult = matcher.group();
1008N/A hasNextPosition = matcher.end();
1008N/A hasNextPattern = matcher.pattern();
1008N/A }
1008N/A
1008N/A private void cacheResult(String result) {
1008N/A hasNextResult = result;
1008N/A hasNextPosition = matcher.end();
1008N/A hasNextPattern = matcher.pattern();
1008N/A }
1008N/A
1008N/A // Clears both regular cache and type cache
1008N/A private void clearCaches() {
1008N/A hasNextPattern = null;
1008N/A typeCache = null;
1008N/A }
1008N/A
1008N/A // Also clears both the regular cache and the type cache
1008N/A private String getCachedResult() {
1008N/A position = hasNextPosition;
1008N/A hasNextPattern = null;
1008N/A typeCache = null;
1008N/A return hasNextResult;
1008N/A }
1008N/A
1008N/A // Also clears both the regular cache and the type cache
1008N/A private void useTypeCache() {
1008N/A if (closed)
1008N/A throw new IllegalStateException("Scanner closed");
1008N/A position = hasNextPosition;
1008N/A hasNextPattern = null;
1008N/A typeCache = null;
1008N/A }
1008N/A
1008N/A // Tries to read more input. May block.
1008N/A private void readInput() {
1008N/A if (buf.limit() == buf.capacity())
1008N/A makeSpace();
1008N/A
1008N/A // Prepare to receive data
1008N/A int p = buf.position();
1008N/A buf.position(buf.limit());
1008N/A buf.limit(buf.capacity());
1008N/A
1008N/A int n = 0;
1008N/A try {
1008N/A n = source.read(buf);
1008N/A } catch (IOException ioe) {
1008N/A lastException = ioe;
1008N/A n = -1;
1008N/A }
1008N/A
1008N/A if (n == -1) {
1008N/A sourceClosed = true;
1008N/A needInput = false;
1008N/A }
1008N/A
1008N/A if (n > 0)
1008N/A needInput = false;
1008N/A
1008N/A // Restore current position and limit for reading
1008N/A buf.limit(buf.position());
1008N/A buf.position(p);
1418N/A }
1418N/A
1418N/A // After this method is called there will either be an exception
1418N/A // or else there will be space in the buffer
1418N/A private boolean makeSpace() {
1418N/A clearCaches();
1418N/A int offset = savedScannerPosition == -1 ?
1418N/A position : savedScannerPosition;
1418N/A buf.position(offset);
1418N/A // Gain space by compacting buffer
1418N/A if (offset > 0) {
1418N/A buf.compact();
1418N/A translateSavedIndexes(offset);
1418N/A position -= offset;
1418N/A buf.flip();
1418N/A return true;
1418N/A }
1418N/A // Gain space by growing buffer
1418N/A int newSize = buf.capacity() * 2;
1008N/A CharBuffer newBuf = CharBuffer.allocate(newSize);
1008N/A newBuf.put(buf);
1008N/A newBuf.flip();
1008N/A translateSavedIndexes(offset);
1008N/A position -= offset;
1008N/A buf = newBuf;
1008N/A matcher.reset(buf);
1008N/A return true;
1008N/A }
1008N/A
1008N/A // When a buffer compaction/reallocation occurs the saved indexes must
1008N/A // be modified appropriately
1008N/A private void translateSavedIndexes(int offset) {
1008N/A if (savedScannerPosition != -1)
1008N/A savedScannerPosition -= offset;
1008N/A }
1008N/A
1008N/A // If we are at the end of input then NoSuchElement;
1008N/A // If there is still input left then InputMismatch
1418N/A private void throwFor() {
1418N/A skipped = false;
1418N/A if ((sourceClosed) && (position == buf.limit()))
1418N/A throw new NoSuchElementException();
1418N/A else
1418N/A throw new InputMismatchException();
1418N/A }
1418N/A
1418N/A // Returns true if a complete token or partial token is in the buffer.
1008N/A // It is not necessary to find a complete token since a partial token
1008N/A // means that there will be another token with or without more input.
1008N/A private boolean hasTokenInBuffer() {
1008N/A matchValid = false;
1008N/A matcher.usePattern(delimPattern);
1008N/A matcher.region(position, buf.limit());
1008N/A
1008N/A // Skip delims first
1008N/A if (matcher.lookingAt())
1008N/A position = matcher.end();
1008N/A
1008N/A // If we are sitting at the end, no more tokens in buffer
1008N/A if (position == buf.limit())
1008N/A return false;
1008N/A
1008N/A return true;
1008N/A }
1008N/A
1008N/A /*
1008N/A * Returns a "complete token" that matches the specified pattern
1008N/A *
1008N/A * A token is complete if surrounded by delims; a partial token
1008N/A * is prefixed by delims but not postfixed by them
1008N/A *
1008N/A * The position is advanced to the end of that complete token
1008N/A *
1008N/A * Pattern == null means accept any token at all
1008N/A *
1008N/A * Triple return:
1008N/A * 1. valid string means it was found
1008N/A * 2. null with needInput=false means we won't ever find it
1008N/A * 3. null with needInput=true means try again after readInput
1008N/A */
1008N/A private String getCompleteTokenInBuffer(Pattern pattern) {
1008N/A matchValid = false;
1008N/A
1008N/A // Skip delims first
1008N/A matcher.usePattern(delimPattern);
1008N/A if (!skipped) { // Enforcing only one skip of leading delims
1008N/A matcher.region(position, buf.limit());
1008N/A if (matcher.lookingAt()) {
1008N/A // If more input could extend the delimiters then we must wait
1008N/A // for more input
1008N/A if (matcher.hitEnd() && !sourceClosed) {
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A // The delims were whole and the matcher should skip them
1008N/A skipped = true;
1008N/A position = matcher.end();
1008N/A }
1008N/A }
1008N/A
1008N/A // If we are sitting at the end, no more tokens in buffer
1008N/A if (position == buf.limit()) {
1008N/A if (sourceClosed)
1008N/A return null;
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A
1008N/A // Must look for next delims. Simply attempting to match the
1008N/A // pattern at this point may find a match but it might not be
1008N/A // the first longest match because of missing input, or it might
1008N/A // match a partial token instead of the whole thing.
1008N/A
1008N/A // Then look for next delims
1008N/A matcher.region(position, buf.limit());
1008N/A boolean foundNextDelim = matcher.find();
1008N/A if (foundNextDelim && (matcher.end() == position)) {
1008N/A // Zero length delimiter match; we should find the next one
1008N/A // using the automatic advance past a zero length match;
1008N/A // Otherwise we have just found the same one we just skipped
1008N/A foundNextDelim = matcher.find();
1008N/A }
1008N/A if (foundNextDelim) {
1008N/A // In the rare case that more input could cause the match
1008N/A // to be lost and there is more input coming we must wait
1008N/A // for more input. Note that hitting the end is okay as long
1008N/A // as the match cannot go away. It is the beginning of the
1008N/A // next delims we want to be sure about, we don't care if
1008N/A // they potentially extend further.
1008N/A if (matcher.requireEnd() && !sourceClosed) {
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A int tokenEnd = matcher.start();
1008N/A // There is a complete token.
1008N/A if (pattern == null) {
1008N/A // Must continue with match to provide valid MatchResult
1008N/A pattern = FIND_ANY_PATTERN;
1008N/A }
1008N/A // Attempt to match against the desired pattern
1008N/A matcher.usePattern(pattern);
1008N/A matcher.region(position, tokenEnd);
1008N/A if (matcher.matches()) {
1008N/A String s = matcher.group();
1008N/A position = matcher.end();
1008N/A return s;
1008N/A } else { // Complete token but it does not match
1008N/A return null;
1008N/A }
1008N/A }
1008N/A
1008N/A // If we can't find the next delims but no more input is coming,
1008N/A // then we can treat the remainder as a whole token
1008N/A if (sourceClosed) {
1008N/A if (pattern == null) {
1008N/A // Must continue with match to provide valid MatchResult
1008N/A pattern = FIND_ANY_PATTERN;
1008N/A }
1008N/A // Last token; Match the pattern here or throw
1008N/A matcher.usePattern(pattern);
1008N/A matcher.region(position, buf.limit());
1008N/A if (matcher.matches()) {
1008N/A String s = matcher.group();
1008N/A position = matcher.end();
1008N/A return s;
1008N/A }
1008N/A // Last piece does not match
1008N/A return null;
1008N/A }
1008N/A
1008N/A // There is a partial token in the buffer; must read more
1008N/A // to complete it
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A
1008N/A // Finds the specified pattern in the buffer up to horizon.
1008N/A // Returns a match for the specified input pattern.
1008N/A private String findPatternInBuffer(Pattern pattern, int horizon) {
1008N/A matchValid = false;
1008N/A matcher.usePattern(pattern);
1008N/A int bufferLimit = buf.limit();
1008N/A int horizonLimit = -1;
1008N/A int searchLimit = bufferLimit;
1008N/A if (horizon > 0) {
1008N/A horizonLimit = position + horizon;
1008N/A if (horizonLimit < bufferLimit)
1008N/A searchLimit = horizonLimit;
1008N/A }
1008N/A matcher.region(position, searchLimit);
1008N/A if (matcher.find()) {
1008N/A if (matcher.hitEnd() && (!sourceClosed)) {
1008N/A // The match may be longer if didn't hit horizon or real end
1008N/A if (searchLimit != horizonLimit) {
1008N/A // Hit an artificial end; try to extend the match
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A // The match could go away depending on what is next
1008N/A if ((searchLimit == horizonLimit) && matcher.requireEnd()) {
1008N/A // Rare case: we hit the end of input and it happens
1008N/A // that it is at the horizon and the end of input is
1008N/A // required for the match.
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A }
1008N/A // Did not hit end, or hit real end, or hit horizon
1008N/A position = matcher.end();
1008N/A return matcher.group();
1008N/A }
1008N/A
1008N/A if (sourceClosed)
1008N/A return null;
1008N/A
1008N/A // If there is no specified horizon, or if we have not searched
1008N/A // to the specified horizon yet, get more input
1008N/A if ((horizon == 0) || (searchLimit != horizonLimit))
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A
1008N/A // Returns a match for the specified input pattern anchored at
1008N/A // the current position
1008N/A private String matchPatternInBuffer(Pattern pattern) {
1008N/A matchValid = false;
1008N/A matcher.usePattern(pattern);
1008N/A matcher.region(position, buf.limit());
1008N/A if (matcher.lookingAt()) {
1008N/A if (matcher.hitEnd() && (!sourceClosed)) {
1008N/A // Get more input and try again
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A position = matcher.end();
1008N/A return matcher.group();
1008N/A }
1155N/A
1008N/A if (sourceClosed)
1008N/A return null;
1008N/A
1008N/A // Read more to find pattern
1008N/A needInput = true;
1008N/A return null;
1008N/A }
1008N/A
1008N/A // Throws if the scanner is closed
1008N/A private void ensureOpen() {
1008N/A if (closed)
1008N/A throw new IllegalStateException("Scanner closed");
1008N/A }
1008N/A
1008N/A // Public methods
1008N/A
1008N/A /**
1008N/A * Closes this scanner.
1008N/A *
1008N/A * <p> If this scanner has not yet been closed then if its underlying
1008N/A * {@linkplain java.lang.Readable readable} also implements the {@link
1008N/A * java.io.Closeable} interface then the readable's <tt>close</tt> method
1008N/A * will be invoked. If this scanner is already closed then invoking this
1008N/A * method will have no effect.
1008N/A *
1008N/A * <p>Attempting to perform search operations after a scanner has
1008N/A * been closed will result in an {@link IllegalStateException}.
1008N/A *
1008N/A */
1008N/A public void close() {
1008N/A if (closed)
1008N/A return;
1008N/A if (source instanceof Closeable) {
1008N/A try {
1008N/A ((Closeable)source).close();
1008N/A } catch (IOException ioe) {
1008N/A lastException = ioe;
1008N/A }
1008N/A }
1008N/A sourceClosed = true;
1008N/A source = null;
1008N/A closed = true;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns the <code>IOException</code> last thrown by this
1008N/A * <code>Scanner</code>'s underlying <code>Readable</code>. This method
1008N/A * returns <code>null</code> if no such exception exists.
1008N/A *
1008N/A * @return the last exception thrown by this scanner's readable
1008N/A */
1008N/A public IOException ioException() {
1008N/A return lastException;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns the <code>Pattern</code> this <code>Scanner</code> is currently
1008N/A * using to match delimiters.
1008N/A *
1008N/A * @return this scanner's delimiting pattern.
1008N/A */
1008N/A public Pattern delimiter() {
1008N/A return delimPattern;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Sets this scanner's delimiting pattern to the specified pattern.
1008N/A *
1008N/A * @param pattern A delimiting pattern
1008N/A * @return this scanner
1008N/A */
1008N/A public Scanner useDelimiter(Pattern pattern) {
1008N/A delimPattern = pattern;
1008N/A return this;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Sets this scanner's delimiting pattern to a pattern constructed from
1008N/A * the specified <code>String</code>.
1008N/A *
1008N/A * <p> An invocation of this method of the form
1008N/A * <tt>useDelimiter(pattern)</tt> behaves in exactly the same way as the
1008N/A * invocation <tt>useDelimiter(Pattern.compile(pattern))</tt>.
1008N/A *
1008N/A * <p> Invoking the {@link #reset} method will set the scanner's delimiter
1008N/A * to the <a href= "#default-delimiter">default</a>.
1008N/A *
1008N/A * @param pattern A string specifying a delimiting pattern
1008N/A * @return this scanner
1008N/A */
1008N/A public Scanner useDelimiter(String pattern) {
1008N/A delimPattern = patternCache.forName(pattern);
1008N/A return this;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns this scanner's locale.
1008N/A *
1008N/A * <p>A scanner's locale affects many elements of its default
1008N/A * primitive matching regular expressions; see
1008N/A * <a href= "#localized-numbers">localized numbers</a> above.
1008N/A *
1008N/A * @return this scanner's locale
1008N/A */
1008N/A public Locale locale() {
1008N/A return this.locale;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Sets this scanner's locale to the specified locale.
1008N/A *
1008N/A * <p>A scanner's locale affects many elements of its default
1008N/A * primitive matching regular expressions; see
1008N/A * <a href= "#localized-numbers">localized numbers</a> above.
1008N/A *
1008N/A * <p>Invoking the {@link #reset} method will set the scanner's locale to
1008N/A * the <a href= "#initial-locale">initial locale</a>.
1008N/A *
1008N/A * @param locale A string specifying the locale to use
1008N/A * @return this scanner
1008N/A */
1008N/A public Scanner useLocale(Locale locale) {
1008N/A if (locale.equals(this.locale))
1008N/A return this;
1008N/A
1008N/A this.locale = locale;
1008N/A DecimalFormat df =
1008N/A (DecimalFormat)NumberFormat.getNumberInstance(locale);
1008N/A DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(locale);
1008N/A
1008N/A // These must be literalized to avoid collision with regex
1008N/A // metacharacters such as dot or parenthesis
1008N/A groupSeparator = "\\" + dfs.getGroupingSeparator();
1008N/A decimalSeparator = "\\" + dfs.getDecimalSeparator();
1008N/A
1008N/A // Quoting the nonzero length locale-specific things
1008N/A // to avoid potential conflict with metacharacters
1008N/A nanString = "\\Q" + dfs.getNaN() + "\\E";
1008N/A infinityString = "\\Q" + dfs.getInfinity() + "\\E";
1008N/A positivePrefix = df.getPositivePrefix();
1008N/A if (positivePrefix.length() > 0)
1008N/A positivePrefix = "\\Q" + positivePrefix + "\\E";
1008N/A negativePrefix = df.getNegativePrefix();
1008N/A if (negativePrefix.length() > 0)
1008N/A negativePrefix = "\\Q" + negativePrefix + "\\E";
1008N/A positiveSuffix = df.getPositiveSuffix();
1008N/A if (positiveSuffix.length() > 0)
1008N/A positiveSuffix = "\\Q" + positiveSuffix + "\\E";
1008N/A negativeSuffix = df.getNegativeSuffix();
1008N/A if (negativeSuffix.length() > 0)
1008N/A negativeSuffix = "\\Q" + negativeSuffix + "\\E";
1008N/A
1008N/A // Force rebuilding and recompilation of locale dependent
1008N/A // primitive patterns
1008N/A integerPattern = null;
1008N/A floatPattern = null;
1008N/A
1008N/A return this;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns this scanner's default radix.
1008N/A *
1008N/A * <p>A scanner's radix affects elements of its default
1008N/A * number matching regular expressions; see
1008N/A * <a href= "#localized-numbers">localized numbers</a> above.
1008N/A *
1008N/A * @return the default radix of this scanner
1008N/A */
1008N/A public int radix() {
1008N/A return this.defaultRadix;
1008N/A }
1008N/A
1008N/A /**
1008N/A * Sets this scanner's default radix to the specified radix.
1008N/A *
1008N/A * <p>A scanner's radix affects elements of its default
1008N/A * number matching regular expressions; see
1008N/A * <a href= "#localized-numbers">localized numbers</a> above.
1008N/A *
1008N/A * <p>If the radix is less than <code>Character.MIN_RADIX</code>
1008N/A * or greater than <code>Character.MAX_RADIX</code>, then an
1008N/A * <code>IllegalArgumentException</code> is thrown.
1008N/A *
1008N/A * <p>Invoking the {@link #reset} method will set the scanner's radix to
1008N/A * <code>10</code>.
1008N/A *
1008N/A * @param radix The radix to use when scanning numbers
1008N/A * @return this scanner
1008N/A * @throws IllegalArgumentException if radix is out of range
1008N/A */
1008N/A public Scanner useRadix(int radix) {
1008N/A if ((radix < Character.MIN_RADIX) || (radix > Character.MAX_RADIX))
1008N/A throw new IllegalArgumentException("radix:"+radix);
1008N/A
1008N/A if (this.defaultRadix == radix)
1008N/A return this;
1008N/A this.defaultRadix = radix;
1008N/A // Force rebuilding and recompilation of radix dependent patterns
1008N/A integerPattern = null;
1008N/A return this;
1008N/A }
1008N/A
1008N/A // The next operation should occur in the specified radix but
1008N/A // the default is left untouched.
1008N/A private void setRadix(int radix) {
1008N/A if (this.radix != radix) {
1008N/A // Force rebuilding and recompilation of radix dependent patterns
1008N/A integerPattern = null;
1528N/A this.radix = radix;
1528N/A }
1528N/A }
1528N/A
1528N/A /**
1528N/A * Returns the match result of the last scanning operation performed
1528N/A * by this scanner. This method throws <code>IllegalStateException</code>
1528N/A * if no match has been performed, or if the last match was
1528N/A * not successful.
1528N/A *
1008N/A * <p>The various <code>next</code>methods of <code>Scanner</code>
1008N/A * make a match result available if they complete without throwing an
1008N/A * exception. For instance, after an invocation of the {@link #nextInt}
1008N/A * method that returned an int, this method returns a
1008N/A * <code>MatchResult</code> for the search of the
1008N/A * <a href="#Integer-regex"><i>Integer</i></a> regular expression
1008N/A * defined above. Similarly the {@link #findInLine},
1008N/A * {@link #findWithinHorizon}, and {@link #skip} methods will make a
1008N/A * match available if they succeed.
1008N/A *
1008N/A * @return a match result for the last match operation
1008N/A * @throws IllegalStateException If no match result is available
1008N/A */
1008N/A public MatchResult match() {
1008N/A if (!matchValid)
1008N/A throw new IllegalStateException("No match result available");
1008N/A return matcher.toMatchResult();
1008N/A }
1008N/A
1008N/A /**
1008N/A * <p>Returns the string representation of this <code>Scanner</code>. The
1087N/A * string representation of a <code>Scanner</code> contains information
1087N/A * that may be useful for debugging. The exact format is unspecified.
1087N/A *
1087N/A * @return The string representation of this scanner
1087N/A */
1087N/A public String toString() {
1087N/A StringBuilder sb = new StringBuilder();
1087N/A sb.append("java.util.Scanner");
1087N/A sb.append("[delimiters=" + delimPattern + "]");
1008N/A sb.append("[position=" + position + "]");
1008N/A sb.append("[match valid=" + matchValid + "]");
1008N/A sb.append("[need input=" + needInput + "]");
1008N/A sb.append("[source closed=" + sourceClosed + "]");
1008N/A sb.append("[skipped=" + skipped + "]");
1008N/A sb.append("[group separator=" + groupSeparator + "]");
1008N/A sb.append("[decimal separator=" + decimalSeparator + "]");
1008N/A sb.append("[positive prefix=" + positivePrefix + "]");
1008N/A sb.append("[negative prefix=" + negativePrefix + "]");
1008N/A sb.append("[positive suffix=" + positiveSuffix + "]");
1008N/A sb.append("[negative suffix=" + negativeSuffix + "]");
1008N/A sb.append("[NaN string=" + nanString + "]");
1008N/A sb.append("[infinity string=" + infinityString + "]");
1008N/A return sb.toString();
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns true if this scanner has another token in its input.
1008N/A * This method may block while waiting for input to scan.
1008N/A * The scanner does not advance past any input.
1008N/A *
1008N/A * @return true if and only if this scanner has another token
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A * @see java.util.Iterator
1008N/A */
1008N/A public boolean hasNext() {
1008N/A ensureOpen();
1008N/A saveState();
1008N/A while (!sourceClosed) {
1008N/A if (hasTokenInBuffer())
1008N/A return revertState(true);
1008N/A readInput();
1418N/A }
1008N/A boolean result = hasTokenInBuffer();
1008N/A return revertState(result);
1008N/A }
1418N/A
1418N/A /**
1418N/A * Finds and returns the next complete token from this scanner.
1418N/A * A complete token is preceded and followed by input that matches
1418N/A * the delimiter pattern. This method may block while waiting for input
1418N/A * to scan, even if a previous invocation of {@link #hasNext} returned
1418N/A * <code>true</code>.
1418N/A *
1418N/A * @return the next token
1418N/A * @throws NoSuchElementException if no more tokens are available
1418N/A * @throws IllegalStateException if this scanner is closed
1418N/A * @see java.util.Iterator
1008N/A */
1008N/A public String next() {
1008N/A ensureOpen();
1418N/A clearCaches();
1418N/A
1418N/A while (true) {
1008N/A String token = getCompleteTokenInBuffer(null);
1008N/A if (token != null) {
1008N/A matchValid = true;
1008N/A skipped = false;
1008N/A return token;
1008N/A }
1008N/A if (needInput)
1008N/A readInput();
1008N/A else
1008N/A throwFor();
1008N/A }
1008N/A }
1008N/A
1008N/A /**
1008N/A * The remove operation is not supported by this implementation of
1008N/A * <code>Iterator</code>.
1008N/A *
1008N/A * @throws UnsupportedOperationException if this method is invoked.
1008N/A * @see java.util.Iterator
1008N/A */
1008N/A public void remove() {
1008N/A throw new UnsupportedOperationException();
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns true if the next token matches the pattern constructed from the
1008N/A * specified string. The scanner does not advance past any input.
1008N/A *
1008N/A * <p> An invocation of this method of the form <tt>hasNext(pattern)</tt>
1008N/A * behaves in exactly the same way as the invocation
1008N/A * <tt>hasNext(Pattern.compile(pattern))</tt>.
1008N/A *
1008N/A * @param pattern a string specifying the pattern to scan
1008N/A * @return true if and only if this scanner has another token matching
1008N/A * the specified pattern
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A */
1008N/A public boolean hasNext(String pattern) {
1008N/A return hasNext(patternCache.forName(pattern));
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns the next token if it matches the pattern constructed from the
1008N/A * specified string. If the match is successful, the scanner advances
1008N/A * past the input that matched the pattern.
1008N/A *
1008N/A * <p> An invocation of this method of the form <tt>next(pattern)</tt>
1008N/A * behaves in exactly the same way as the invocation
1008N/A * <tt>next(Pattern.compile(pattern))</tt>.
1008N/A *
1548N/A * @param pattern a string specifying the pattern to scan
1548N/A * @return the next token
1548N/A * @throws NoSuchElementException if no such tokens are available
1548N/A * @throws IllegalStateException if this scanner is closed
1548N/A */
1548N/A public String next(String pattern) {
1548N/A return next(patternCache.forName(pattern));
1548N/A }
1548N/A
1548N/A /**
1548N/A * Returns true if the next complete token matches the specified pattern.
1548N/A * A complete token is prefixed and postfixed by input that matches
1548N/A * the delimiter pattern. This method may block while waiting for input.
1548N/A * The scanner does not advance past any input.
1548N/A *
1548N/A * @param pattern the pattern to scan for
1548N/A * @return true if and only if this scanner has another token matching
1548N/A * the specified pattern
1548N/A * @throws IllegalStateException if this scanner is closed
1548N/A */
1548N/A public boolean hasNext(Pattern pattern) {
1548N/A ensureOpen();
1548N/A if (pattern == null)
1548N/A throw new NullPointerException();
1548N/A hasNextPattern = null;
1548N/A saveState();
1548N/A
1548N/A while (true) {
1548N/A if (getCompleteTokenInBuffer(pattern) != null) {
1548N/A matchValid = true;
1548N/A cacheResult();
1548N/A return revertState(true);
1548N/A }
1548N/A if (needInput)
1548N/A readInput();
1548N/A else
1548N/A return revertState(false);
1548N/A }
1548N/A }
1548N/A
1548N/A /**
1548N/A * Returns the next token if it matches the specified pattern. This
1548N/A * method may block while waiting for input to scan, even if a previous
1548N/A * invocation of {@link #hasNext(Pattern)} returned <code>true</code>.
1548N/A * If the match is successful, the scanner advances past the input that
1548N/A * matched the pattern.
1548N/A *
1548N/A * @param pattern the pattern to scan for
1548N/A * @return the next token
1548N/A * @throws NoSuchElementException if no more tokens are available
1548N/A * @throws IllegalStateException if this scanner is closed
1548N/A */
1548N/A public String next(Pattern pattern) {
1548N/A ensureOpen();
1548N/A if (pattern == null)
1548N/A throw new NullPointerException();
1548N/A
1548N/A // Did we already find this pattern?
1548N/A if (hasNextPattern == pattern)
1008N/A return getCachedResult();
1008N/A clearCaches();
1008N/A
1008N/A // Search for the pattern
1008N/A while (true) {
1008N/A String token = getCompleteTokenInBuffer(pattern);
1008N/A if (token != null) {
1008N/A matchValid = true;
1008N/A skipped = false;
1008N/A return token;
1008N/A }
1008N/A if (needInput)
1008N/A readInput();
1008N/A else
1008N/A throwFor();
1008N/A }
1008N/A }
1008N/A
1008N/A /**
1008N/A * Returns true if there is another line in the input of this scanner.
1008N/A * This method may block while waiting for input. The scanner does not
1008N/A * advance past any input.
1008N/A *
1008N/A * @return true if and only if this scanner has another line of input
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A */
1008N/A public boolean hasNextLine() {
1008N/A saveState();
1008N/A
1008N/A String result = findWithinHorizon(linePattern(), 0);
1008N/A if (result != null) {
1008N/A MatchResult mr = this.match();
1008N/A String lineSep = mr.group(1);
1008N/A if (lineSep != null) {
1008N/A result = result.substring(0, result.length() -
1008N/A lineSep.length());
1008N/A cacheResult(result);
1008N/A
1008N/A } else {
1008N/A cacheResult();
1008N/A }
1008N/A }
1008N/A revertState();
1008N/A return (result != null);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Advances this scanner past the current line and returns the input
1008N/A * that was skipped.
1008N/A *
1008N/A * This method returns the rest of the current line, excluding any line
1008N/A * separator at the end. The position is set to the beginning of the next
1008N/A * line.
1008N/A *
1008N/A * <p>Since this method continues to search through the input looking
1008N/A * for a line separator, it may buffer all of the input searching for
1008N/A * the line to skip if no line separators are present.
1008N/A *
1008N/A * @return the line that was skipped
1008N/A * @throws NoSuchElementException if no line was found
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A */
1008N/A public String nextLine() {
1008N/A if (hasNextPattern == linePattern())
1008N/A return getCachedResult();
1008N/A clearCaches();
1008N/A
1008N/A String result = findWithinHorizon(linePattern, 0);
1008N/A if (result == null)
1008N/A throw new NoSuchElementException("No line found");
1008N/A MatchResult mr = this.match();
1008N/A String lineSep = mr.group(1);
1008N/A if (lineSep != null)
1008N/A result = result.substring(0, result.length() - lineSep.length());
1008N/A if (result == null)
1008N/A throw new NoSuchElementException();
1008N/A else
1008N/A return result;
1008N/A }
1008N/A
1008N/A // Public methods that ignore delimiters
1008N/A
1008N/A /**
1008N/A * Attempts to find the next occurrence of a pattern constructed from the
1008N/A * specified string, ignoring delimiters.
1008N/A *
1008N/A * <p>An invocation of this method of the form <tt>findInLine(pattern)</tt>
1008N/A * behaves in exactly the same way as the invocation
1008N/A * <tt>findInLine(Pattern.compile(pattern))</tt>.
1008N/A *
1008N/A * @param pattern a string specifying the pattern to search for
1008N/A * @return the text that matched the specified pattern
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A */
1008N/A public String findInLine(String pattern) {
1008N/A return findInLine(patternCache.forName(pattern));
1008N/A }
1008N/A
1008N/A /**
1008N/A * Attempts to find the next occurrence of the specified pattern ignoring
1008N/A * delimiters. If the pattern is found before the next line separator, the
1008N/A * scanner advances past the input that matched and returns the string that
1008N/A * matched the pattern.
1008N/A * If no such pattern is detected in the input up to the next line
1008N/A * separator, then <code>null</code> is returned and the scanner's
1008N/A * position is unchanged. This method may block waiting for input that
1008N/A * matches the pattern.
1008N/A *
1008N/A * <p>Since this method continues to search through the input looking
1008N/A * for the specified pattern, it may buffer all of the input searching for
1008N/A * the desired token if no line separators are present.
1008N/A *
1008N/A * @param pattern the pattern to scan for
1008N/A * @return the text that matched the specified pattern
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A */
1008N/A public String findInLine(Pattern pattern) {
1008N/A ensureOpen();
1008N/A if (pattern == null)
1008N/A throw new NullPointerException();
1008N/A clearCaches();
1008N/A // Expand buffer to include the next newline or end of input
1008N/A int endPosition = 0;
1008N/A saveState();
1008N/A while (true) {
1008N/A String token = findPatternInBuffer(separatorPattern(), 0);
1008N/A if (token != null) {
1008N/A endPosition = matcher.start();
1008N/A break; // up to next newline
1008N/A }
1008N/A if (needInput) {
1008N/A readInput();
1008N/A } else {
1008N/A endPosition = buf.limit();
1008N/A break; // up to end of input
1008N/A }
1008N/A }
1008N/A revertState();
1008N/A int horizonForLine = endPosition - position;
1008N/A // If there is nothing between the current pos and the next
1008N/A // newline simply return null, invoking findWithinHorizon
1008N/A // with "horizon=0" will scan beyond the line bound.
1008N/A if (horizonForLine == 0)
1008N/A return null;
1008N/A // Search for the pattern
1008N/A return findWithinHorizon(pattern, horizonForLine);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Attempts to find the next occurrence of a pattern constructed from the
1008N/A * specified string, ignoring delimiters.
1008N/A *
1008N/A * <p>An invocation of this method of the form
1008N/A * <tt>findWithinHorizon(pattern)</tt> behaves in exactly the same way as
1008N/A * the invocation
1008N/A * <tt>findWithinHorizon(Pattern.compile(pattern, horizon))</tt>.
1008N/A *
1008N/A * @param pattern a string specifying the pattern to search for
1008N/A * @return the text that matched the specified pattern
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A * @throws IllegalArgumentException if horizon is negative
1008N/A */
1008N/A public String findWithinHorizon(String pattern, int horizon) {
1008N/A return findWithinHorizon(patternCache.forName(pattern), horizon);
1008N/A }
1008N/A
1008N/A /**
1008N/A * Attempts to find the next occurrence of the specified pattern.
1008N/A *
1008N/A * <p>This method searches through the input up to the specified
1008N/A * search horizon, ignoring delimiters. If the pattern is found the
1008N/A * scanner advances past the input that matched and returns the string
1008N/A * that matched the pattern. If no such pattern is detected then the
1008N/A * null is returned and the scanner's position remains unchanged. This
1008N/A * method may block waiting for input that matches the pattern.
1008N/A *
1008N/A * <p>A scanner will never search more than <code>horizon</code> code
1008N/A * points beyond its current position. Note that a match may be clipped
1008N/A * by the horizon; that is, an arbitrary match result may have been
1008N/A * different if the horizon had been larger. The scanner treats the
1008N/A * horizon as a transparent, non-anchoring bound (see {@link
1008N/A * Matcher#useTransparentBounds} and {@link Matcher#useAnchoringBounds}).
1008N/A *
1008N/A * <p>If horizon is <code>0</code>, then the horizon is ignored and
1008N/A * this method continues to search through the input looking for the
1008N/A * specified pattern without bound. In this case it may buffer all of
1008N/A * the input searching for the pattern.
1008N/A *
1008N/A * <p>If horizon is negative, then an IllegalArgumentException is
1008N/A * thrown.
1008N/A *
1008N/A * @param pattern the pattern to scan for
1008N/A * @return the text that matched the specified pattern
1008N/A * @throws IllegalStateException if this scanner is closed
1008N/A * @throws IllegalArgumentException if horizon is negative
1008N/A */
1087N/A 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</tt> 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</code> by using a pattern that can
* match nothing, e.g., <code>sc.skip("[ \t]*")</code>.
*
* @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 <tt>skip(pattern)</tt>
* behaves in exactly the same way as the invocation
* <tt>skip(Pattern.compile(pattern))</tt>.
*
* @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</code>
* 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</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextByte()</tt> behaves in exactly the same way as the
* invocation <tt>nextByte(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>byte</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>byte</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextShort()</tt> behaves in exactly the same way as the
* invocation <tt>nextShort(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>short</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>short</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextInt()</tt> behaves in exactly the same way as the
* invocation <tt>nextInt(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>int</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into an <tt>int</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
*
* <p> An invocation of this method of the form
* <tt>nextLong()</tt> behaves in exactly the same way as the
* invocation <tt>nextLong(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>long</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>long</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Float-regex"><i>Float</i></a> regular expression defined above
* then the token is converted into a <tt>float</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float</i>
* 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</tt>.
* This method will throw <code>InputMismatchException</code>
* 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 <a
* href="#Float-regex"><i>Float</i></a> regular expression defined above
* then the token is converted into a <tt>double</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Float</i>
* 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</code> 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</code>
* @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</code> 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</code>
* @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()</tt> behaves in exactly the same way as the
* invocation <tt>nextBigInteger(radix)</tt>, where <code>radix</code>
* is the default radix of this scanner.
*
* @return the <tt>BigInteger</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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 <a
* href="#Integer-regex"><i>Integer</i></a> regular expression defined
* above then the token is converted into a <tt>BigInteger</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Integer</i>
* 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</code> 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</code>
* @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 <a
* href="#Decimal-regex"><i>Decimal</i></a> regular expression defined
* above then the token is converted into a <tt>BigDecimal</tt> 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</tt> scanned from the input
* @throws InputMismatchException
* if the next token does not match the <i>Decimal</i>
* 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()</tt> behaves in exactly the same way as the
* invocation
*
* <blockquote><pre>
* scanner.useDelimiter("\\p{javaWhitespace}+")
* .useLocale(Locale.getDefault())
* .useRadix(10);
* </pre></blockquote>
*
* @return this scanner
*
* @since 1.6
*/
public Scanner reset() {
delimPattern = WHITESPACE_PATTERN;
useLocale(Locale.getDefault(Locale.Category.FORMAT));
useRadix(10);
clearCaches();
return this;
}
}