NoSuchElementException if no more tokens are available
Do not use scanner.close()
<- source of your error!
remove the lines scanner.close()
and newScanner.close()
From Java DOCs:
When a Scanner is closed, it will close its input source if the source implements the Closeable interface.
Which means it closes the System.in
– bad choice!
From source code of Scanner.java
in JDK, throwFor()
is:
private void throwFor() { skipped = false; if ((sourceClosed) && (position == buf.limit())) throw new NoSuchElementException(); else throw new InputMismatchException(); }
Clearly, if we have reached the end of input, OR if the source is closed, then we get the NoSuchElementException()
. I am pretty sure the one at IDEONE has happened because of position == buf.limit()
rather than sourceClosed