Skip to content
Advertisement

java.util.NoSuchElementException error on multiple while statements

Screenshot of error message

Getting this error when I run my code, note that it finds a problem at line 37, but I cannot figure out what it is. Running the first iteration of the scanner method (for input 1) worked fine, and yielded the proper output, but none of the consecutive ones have, and I’ve been stuck on that issue. Code is below:

JavaScript

Advertisement

Answer

The exception NoSuchElementException in your case is caused by trying to use nextInt() on a file/input that has no more int’s left to read, see the Javadoc:

Thrown by various accessor methods to indicate that the element being requested does not exist.

The reason you get the issue is because every time you call nextInt() in actually uses up an int and moves onto the next one.

So instead of this where you call nextInt() over and over in the if/else if:

JavaScript

You need to do call nextInt() once and assign it to a value then use that value:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement