CommanderGumball CommanderGumball - 1 year ago 90
Java Question

Java; As soon as I encounter an input I get "Exception in thread "main" java.util.NoSuchElementException"

I'm making a very basic database management program, I've got a scanner for name and value working fine in one class(,

public static void createNewAccount() {

Scanner newScan = new Scanner(;
System.out.print("Enter name: ");
String inputName = newScan.nextLine();
name = inputName;
System.out.print("Enter the initial value: ");
double inputBalance = newScan.nextInt();
System.out.println("... successfully created new account.");


Account newAccount = new Account(inputName, inputBalance);


Debugging this little bit works fine, but when I jump back into my other class ( and hit my switch statement I'm stuck with this error, and I can't seem to find an answer anywhere else (Lots of people get the same error, but for different reasons it seems?)

Scanner in = new Scanner(;

//Debugging statement #1 here works fine, can access other Class
Menu Options
System.out.println(">> Select your option (1-6)");
choice = in.nextInt();

//Debugging statement #2 here doesn't display, this is where the error hits.

switch (choice) {
... Cases

This is the console output:

>> Select your option (1-6)
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Management.main(

I'm confused as to why this is happening because I've got another scanner that works perfectly fine.

Answer Source

When you close a Scanner it also closes the underlying InputStream. So if you create a scanner using at an earlier point in the program and then close that scanner, it would close

Once an inputstream has been closed it can no longer be read from and attempts to do so will cause a NoSuchElementException.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download