Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h3>Overview of <code>Scanner.hasNextXXX</code> methods</h3> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html" rel="noreferrer"><code>java.util.Scanner</code></a> has many <code>hasNextXXX</code> methods that can be used to validate input. Here's a brief overview of all of them:</p> <ul> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNext%28%29" rel="noreferrer"><code>hasNext()</code></a> - does it have <em>any</em> token at all?</li> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextLine%28%29" rel="noreferrer"><code>hasNextLine()</code></a> - does it have another line of input?</li> <li>For Java primitives <ul> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29" rel="noreferrer"><code>hasNextInt()</code></a> - does it have a token that can be parsed into an <code>int</code>?</li> <li>Also available are <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextDouble%28%29" rel="noreferrer"><code>hasNextDouble()</code></a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextFloat%28%29" rel="noreferrer"><code>hasNextFloat()</code></a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextByte%28%29" rel="noreferrer"><code>hasNextByte()</code></a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextShort%28%29" rel="noreferrer"><code>hasNextShort()</code></a>, <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextLong%28%29" rel="noreferrer"><code>hasNextLong()</code></a>, and <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextBoolean%28%29" rel="noreferrer"><code>hasNextBoolean()</code></a></li> <li>As bonus, there's also <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextBigInteger%28%29" rel="noreferrer"><code>hasNextBigInteger()</code></a> and <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNextBigDecimal%28%29" rel="noreferrer"><code>hasNextBigDecimal()</code></a></li> <li>The integral types also has overloads to specify radix (for e.g. hexadecimal)</li> </ul></li> <li>Regular expression-based <ul> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNext%28java.lang.String%29" rel="noreferrer"><code>hasNext(String pattern)</code></a></li> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNext%28java.lang.String%29" rel="noreferrer"><code>hasNext(Pattern pattern)</code></a> is the <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#compile%28java.lang.String%29" rel="noreferrer"><code>Pattern.compile</code></a> overload</li> </ul></li> </ul> <p><code>Scanner</code> is capable of more, enabled by the fact that it's regex-based. One important feature is <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#useDelimiter%28java.lang.String%29" rel="noreferrer"><code>useDelimiter(String pattern)</code></a>, which lets you define what <em>pattern</em> separates your tokens. There are also <code>find</code> and <code>skip</code> methods that <em>ignores</em> delimiters.</p> <p>The following discussion will keep the regex as simple as possible, so the focus remains on <code>Scanner</code>.</p> <hr> <h3>Example 1: Validating positive ints</h3> <p>Here's a simple example of using <code>hasNextInt()</code> to validate positive <code>int</code> from the input.</p> <pre><code>Scanner sc = new Scanner(System.in); int number; do { System.out.println("Please enter a positive number!"); while (!sc.hasNextInt()) { System.out.println("That's not a number!"); sc.next(); // this is important! } number = sc.nextInt(); } while (number &lt;= 0); System.out.println("Thank you! Got " + number); </code></pre> <p>Here's an example session:</p> <blockquote> <p><strong><em>Please enter a positive number!</em></strong><br> five<br> <strong><em>That's not a number!</em></strong><br> -3<br> <strong><em>Please enter a positive number!</em></strong><br> 5<br> <strong><em>Thank you! Got 5</em></strong></p> </blockquote> <p>Note how much easier <code>Scanner.hasNextInt()</code> is to use compared to the more verbose <code>try/catch</code> <a href="http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29" rel="noreferrer"><code>Integer.parseInt</code></a>/<a href="http://java.sun.com/javase/6/docs/api/java/lang/NumberFormatException.html" rel="noreferrer"><code>NumberFormatException</code></a> combo. By contract, a <code>Scanner</code> <em>guarantees</em> that if it <code>hasNextInt()</code>, then <code>nextInt()</code> will peacefully give you that <code>int</code>, and will <em>not</em> throw any <code>NumberFormatException</code>/<code>InputMismatchException</code>/<code>NoSuchElementException</code>.</p> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input">How to use Scanner to accept only valid int as input </a></li> <li><a href="https://stackoverflow.com/questions/2496239/how-do-i-keep-a-scanner-from-throwing-exceptions-when-the-wrong-type-is-entered">How do I keep a scanner from throwing exceptions when the wrong type is entered? (java) </a></li> </ul> <hr> <h3>Example 2: Multiple <code>hasNextXXX</code> on the same token</h3> <p>Note that the snippet above contains a <code>sc.next()</code> statement to advance the <code>Scanner</code> until it <code>hasNextInt()</code>. It's important to realize that <strong><em>none</em> of the</strong> <code>hasNextXXX</code> <strong>methods advance the</strong> <code>Scanner</code> <strong>past any input!</strong> You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!</p> <p>This has two consequences:</p> <ul> <li>If you need to skip the "garbage" input that fails your <code>hasNextXXX</code> test, then you need to advance the <code>Scanner</code> one way or another (e.g. <code>next()</code>, <code>nextLine()</code>, <code>skip</code>, etc).</li> <li>If one <code>hasNextXXX</code> test fails, you can <em>still</em> test if it perhaps <code>hasNextYYY</code>!</li> </ul> <p>Here's an example of performing multiple <code>hasNextXXX</code> tests.</p> <pre><code>Scanner sc = new Scanner(System.in); while (!sc.hasNext("exit")) { System.out.println( sc.hasNextInt() ? "(int) " + sc.nextInt() : sc.hasNextLong() ? "(long) " + sc.nextLong() : sc.hasNextDouble() ? "(double) " + sc.nextDouble() : sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() : "(String) " + sc.next() ); } </code></pre> <p>Here's an example session:</p> <blockquote> <p>5<br> <strong><em>(int) 5</em></strong><br> false<br> <strong><em>(boolean) false</em></strong><br> blah<br> <strong><em>(String) blah</em></strong><br> 1.1<br> <strong><em>(double) 1.1</em></strong><br> 100000000000<br> <strong><em>(long) 100000000000</em></strong><br> exit </p> </blockquote> <p>Note that the order of the tests matters. If a <code>Scanner</code> <code>hasNextInt()</code>, then it also <code>hasNextLong()</code>, but it's not necessarily <code>true</code> the other way around. More often than not you'd want to do the more specific test before the more general test.</p> <hr> <h3>Example 3 : Validating vowels</h3> <p><code>Scanner</code> has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.</p> <pre><code>Scanner sc = new Scanner(System.in); System.out.println("Please enter a vowel, lowercase!"); while (!sc.hasNext("[aeiou]")) { System.out.println("That's not a vowel!"); sc.next(); } String vowel = sc.next(); System.out.println("Thank you! Got " + vowel); </code></pre> <p>Here's an example session:</p> <blockquote> <p><strong><em>Please enter a vowel, lowercase!</em></strong><br> 5<br> <strong><em>That's not a vowel!</em></strong><br> z<br> <strong><em>That's not a vowel!</em></strong><br> e<br> <strong><em>Thank you! Got e</em></strong></p> </blockquote> <p>In regex, as a Java string literal, the pattern <code>"[aeiou]"</code> is what is called a "character class"; it matches any of the letters <code>a</code>, <code>e</code>, <code>i</code>, <code>o</code>, <code>u</code>. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the <code>Scanner</code>.</p> <h3>API links</h3> <ul> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#hasNext%28java.lang.String%29" rel="noreferrer"><code>hasNext(String pattern)</code></a> - Returns <code>true</code> if the next token matches the pattern constructed from the specified string.</li> <li><a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html" rel="noreferrer"><code>java.util.regex.Pattern</code></a></li> </ul> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/3043306/reading-a-single-char-in-java/">Reading a single char in Java</a></li> </ul> <h3>References</h3> <ul> <li><a href="http://java.sun.com/docs/books/tutorial/essential/regex/" rel="noreferrer">Java Tutorials/Essential Classes/Regular Expressions</a></li> <li><a href="http://www.regular-expressions.info/charclass.html" rel="noreferrer">regular-expressions.info/Character Classes</a></li> </ul> <hr> <h3>Example 4: Using two <code>Scanner</code> at once</h3> <p>Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use <em>two</em> <code>Scanner</code>, where the second <code>Scanner</code> takes the <code>nextLine()</code> from the first <code>Scanner</code> as input. Here's an example:</p> <pre><code>Scanner sc = new Scanner(System.in); System.out.println("Give me a bunch of numbers in a line (or 'exit')"); while (!sc.hasNext("exit")) { Scanner lineSc = new Scanner(sc.nextLine()); int sum = 0; while (lineSc.hasNextInt()) { sum += lineSc.nextInt(); } System.out.println("Sum is " + sum); } </code></pre> <p>Here's an example session:</p> <blockquote> <p><strong><em>Give me a bunch of numbers in a line (or 'exit')</em></strong><br> 3 4 5<br> <strong><em>Sum is 12</em></strong><br> 10 100 a million dollar<br> <strong><em>Sum is 110</em></strong><br> wait what?<br> <strong><em>Sum is 0</em></strong><br> exit</p> </blockquote> <p>In addition to <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#Scanner%28java.lang.String%29" rel="noreferrer"><code>Scanner(String)</code></a> constructor, there's also <a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html#Scanner%28java.io.File%29" rel="noreferrer"><code>Scanner(java.io.File)</code></a> among others.</p> <hr> <h3>Summary</h3> <ul> <li><code>Scanner</code> provides a rich set of features, such as <code>hasNextXXX</code> methods for validation.</li> <li>Proper usage of <code>hasNextXXX/nextXXX</code> in combination means that a <code>Scanner</code> will <strong>NEVER</strong> throw an <code>InputMismatchException</code>/<code>NoSuchElementException</code>.</li> <li>Always remember that <code>hasNextXXX</code> does not advance the <code>Scanner</code> past any input.</li> <li>Don't be shy to create multiple <code>Scanner</code> if necessary. Two simple <code>Scanner</code> is often better than one overly complex <code>Scanner</code>.</li> <li>Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any <code>Scanner</code> method that takes a <code>String pattern</code> argument is regex-based. <ul> <li><em>Tip</em>: an easy way to turn any <code>String</code> into a literal pattern is to <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#quote%28java.lang.String%29" rel="noreferrer"><code>Pattern.quote</code></a> it.</li> </ul></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload