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