-2
int selection;
    while (true) {
        selection = printing();
        if (selection == 4) {

            id = starting();

            if (id < 1 || id > 10) {
                if (id == -20150901) {
                    System.out.println("Exit code entered");
                    break;
                }

                id = incorrectId(id);
            }
        }


    }


public static int printing(){
    Scanner sc = new Scanner(System.in);
    System.out.print("Main menu\n1: check balance\n2: withdraw\n3: deposit\n4: exit\nEnter a choice: ");
    System.out.print("Enter a choice: ");
    int selection = sc.nextInt();
    return selection;
}

This is part of my java code. The NoElementException occured in the third line. If the whole code is needed, I will copy and paste here and explain what it is about. How can I solve this exception? I want to get keyboard input every time the loop starts.

Thank you.

Alicia May
  • 43
  • 5
  • _Which_ third line, the top, or the `main()` method? Have you poked around here on SO for help on this problem before posting your question? – Tim Biegeleisen Dec 21 '17 at 02:14
  • `nextInt()` throws a `NoSuchElementException` "if input is exhausted", according to the spec. So your standard input must be empty. What is the standard input to your program? – bcsb1001 Dec 21 '17 at 02:15

1 Answers1

0

Your code creates a new Scanner wrapping System.in each time you call printing(). This is incorrect. Instead, your application should create exactly one Scanner wrapping System.in, save it somewhere, and reuse it for each printing() call and all other places where you are reading from System.in.

The problem with creating multiple Scanner objects is that that the hashNext* and next* methods can cause characters to be "read ahead" characters into the Scanner's buffer. So the first printing() could "consume" all characters.


Now this may not be the actual cause of your problem. Other possible causes could be:

  • standard input could be empty, or
  • you may be (directly or indirectly) closing the System.in in some other part of the code.

However, the problem I identified is a bug that would cause application failures in other contexts ... and it is advisable to understand and fix it.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thank you. I tried to put Scanner sc = new Scanner(System.in); just after the class declaration, then the problem occured: cannot be referenced from a static context. So I changed static to default. Then the main could not resolve the methods..... – Alicia May Dec 21 '17 at 15:24
  • You need to review your lecture notes on what `static` means and how static and instance variables work. A static *variable* can be accessed from a static method or an instance method. An instance variable can only be referenced from an instance method if you tell the compiler *which instance you are talking about*. – Stephen C Dec 21 '17 at 23:40