liam12808
liam12808

Reputation: 109

While loop NoSuchElementException integer input java

I'm having some trouble with a menu program I am writing for my java class. After one program is run, when the program goes to do a second loop it throws a NoSuchElementException on the line where it is supposed to take the user's input for the next program they want to run. I'm assuming it has something to do with the scanner getting messed up but I can't find the issue. Anyone have any ideas?

public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    String pin;
    int selection = 0;

    boolean valid = false;
    do {
        System.out.print("Please enter the password: ");
        pin = console.nextLine();
        valid = checkPassword(pin);
    } while (!valid);

    while (selection != 4 && valid == true) {       
        System.out.printf("%nPlease select a number from the menu below %n1: Wage "
            + "Calculator 2: Tip Calculator 3: Grocery Discount 4: Exit %n");

        selection = console.nextInt();

        if (selection == 1) { 
            calc_wages();
        } else if (selection == 2) {
            calc_tip();
        } else if (selection == 3) {
            System.out.print("We haven't gotten this far yet");
        } else if (selection == 4){
            System.out.print("Thank you for using the program.");
            break;
        } else {
            System.out.print("There is no option for what you entered. Try again");
        }
        selection = 0;
    }
}//main

Upvotes: 0

Views: 167

Answers (1)

forpas
forpas

Reputation: 164064

Your code so far is fine.
From what you're saying the problem starts after the user makes a selection.
In calc_wages() and/or calc_tip() it's possible that you use another Scanner object to get the user's input.
This is a source of problems.
Declare 1 Scanner object at the class level and use it throughout you code and close it only when it is no longer needed.

Upvotes: 1

Related Questions