CommanderGumball
CommanderGumball

Reputation: 13

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(Account.java),

public static void createNewAccount() {

    Scanner newScan = new Scanner(System.in);
    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.");

    keyScan.close();


    Account newAccount = new Account(inputName, inputBalance);

}

Debugging this little bit works fine, but when I jump back into my other class (Management.java) 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(System.in);

    Account.createAccount();
//Debugging statement #1 here works fine, can access other Class
do{
        /*
        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 java.util.Scanner.next(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at java.util.Scanner.nextInt(Unknown Source)
        at Management.main(Management.java:30)

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

Upvotes: 1

Views: 194

Answers (1)

Kiskae
Kiskae

Reputation: 25593

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

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

Upvotes: 4

Related Questions