Exception in thread main java.util.NoSuchElementException

Exception in thread main java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results.

The solution: For console apps, use a single Scanner to read from System.in.

Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine().

See: Do not create multiple buffered wrappers on a single InputStream

The nextInt() method leaves the n (end line) symbol and is picked up immediately by nextLine(), skipping over the next input. What you want to do is use nextLine() for everything, and parse it later:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

This is by far the easiest way to avoid problems–dont mix your next methods. Use only nextLine() and then parse ints or separate words afterwards.

Also, make sure you use only one Scanner if your are only using one terminal for input. That could be another reason for the exception.

Last note: compare a String with the .equals() function, not the == operator.

if (playAgain == yes); // Causes problems
if (playAgain.equals(yes)); // Works every time

Exception in thread main java.util.NoSuchElementException

simply dont close in

remove in.close() from your code.

Leave a Reply

Your email address will not be published.