SalehK
SalehK

Reputation: 61

Infinite Looping when creating menu in Java

Im starting to learn Java on my own and wanted to see if i could create a basic menu, but i keep getting an infinite loop after picking an option. Any suggestions?

Scanner menu = new Scanner(System.in);
    System.out.println("1. Print Name");
    System.out.println("2. Print Age");
    System.out.println("3. Print City");
    System.out.println("4. Quit");
    int choice = menu.nextInt();
    do {

        if (choice == 1) {
            System.out.println("Saleh Kaddoura");
        }
        else if (choice == 2) {
            System.out.println("20");
        }
        else if (choice == 3) {
            System.out.println("Santa Clara");
        }
        else {
            System.out.println("That is not a Valid Option!");
        }  
    } while(choice != 4);
    menu.close();

When i pick 1 it'll get stuck in an infinite loop printing my name. I have the conditional statements in a do while loop so the menu doesn't exit unless the quit option is picked.

Upvotes: 0

Views: 749

Answers (1)

The line that updates the choice variable should be inside the loop:

int choice;
do {
    choice = menu.nextInt();
    // ...
} while(choice != 4);

Otherwise, menu.nextInt() will only run once, no more numbers will be read after the first one and the value of choice won't change, so choice != 4 will always be true (unless you pick 4 the first time).

Upvotes: 1

Related Questions