0

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
nbrooks
  • 18,126
  • 5
  • 54
  • 66
liam12808
  • 109
  • 6
  • 1
    Can you show the code for `calc_wages();` and `calc_tip();`? Do you close the `Scanner` at any point in those two methods? – GBlodgett Dec 02 '18 at 20:29
  • Please post the stacktrace. – Ramsay Domloge Dec 02 '18 at 20:42
  • 1
    Possible duplicate of [How to use java.util.Scanner to correctly read user input from System.in and act on it?](https://stackoverflow.com/questions/26446599/how-to-use-java-util-scanner-to-correctly-read-user-input-from-system-in-and-act) – nbrooks Dec 02 '18 at 20:55

1 Answers1

1

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.

forpas
  • 160,666
  • 10
  • 38
  • 76
  • I do have scanners in the other methods but they are named differently and are closed after use. I thought this would prevent any issues is that not the case? – liam12808 Dec 02 '18 at 21:02
  • I think this causes your problems. As I mention in my answer, declare only 1 Scanner at the class level and use this object only. – forpas Dec 02 '18 at 21:04