Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you enter a token which is not a number, calling nextInt does not move the scanner beyond the token. As a result, it's just reading the same token over and over.</p> <p>Here's the documentation for nextInt: <a href="http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28%29" rel="nofollow">http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28%29</a> (although the relevant behavior is actually described in the version which takes an argument, here: <a href="http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28int%29" rel="nofollow">http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html#nextInt%28int%29</a> )</p> <p>So, to give you a quick example, let's assume that the input string is <code>"1 2 Foo"</code>. I will add an X to show where the Scanner is currently positioned. It starts out <code>"X1 2 Foo"</code>. Then the first call to <code>input.nextInt()</code> happens. It returns 1 and now we're at <code>"1 X2 Foo"</code>. Then the second call to <code>input.nextInt()</code> happens. It returns 2 and now we're at <code>"1 2 XFoo"</code>. Then the third call to <code>input.nextInt()</code> happens. It doesn't return, but rather throws an InputMismatchException and it also doesn't advance the Scanner. So we're still at <code>"1 2 XFoo"</code>. So when we call it a fourth or fifth time, the same thing happens.</p> <p>To solve this problem, an <code>input.next()</code> call will consume the next token, whatever it is. After this call, in our example, we would be at <code>"1 2 FooX"</code>.</p> <p>Note, however, that the call to <code>input.next()</code> can also still throw exceptions. Specifically, it can throw IllegalStateException if the Scanner is closed (which shouldn't happen in your code) or NoSuchElementException if the Scanner has reached the end of input (which won't happen if you're reading in from the keyboard, as I assume that you are). But just to be safe, you should either catch those errors and break out of the loop or not catch them and instead declare them as thrown by your method.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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