Simple Menus Using Do-while Loops Java



  • Hello All, I am trying to make a simple menu using a do-while loop in java. My code looks like this:

        Scanner scanChoice = new Scanner(System.in);
        do {
            System.out.println("Pick an option. 1 2 or 3.");
            System.out.println("1. Apple");
            System.out.println("2. Pear");
            System.out.println("3. Pineapple");
    
            choice = scanChoice.nextInt();
        } while (choice < 1 || choice > 3);
    
        System.out.println("You picked " + choice);
    

    The problem is, every time I try to run it on online compiler here, it throws "java.util.NoSuchElementException". The full error is below:

    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)
    at mainPackage.Main.fruitMenu(Main.java:135)
    at mainPackage.Main.main(Main.java:103)
    

    I know that this is because scanChoice.hasNextInt() returns false, but I'm not sure how to fix this. When I add an if statement (if (scanChoice.hasNextInt())), the method scanChoice.hasNextInt() still returns false, so it just passes over the line that initializes the variable choice, and that variable never gets initialized.

    Does anyone suggest to me, how to fix this?

    Thanks in Advance!


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.