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(;
        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(
    at java.util.Scanner.nextInt(
    at java.util.Scanner.nextInt(
    at mainPackage.Main.fruitMenu(
    at mainPackage.Main.main(

    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.