₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,153 members, 8,420,580 topics. Date: Friday, 05 June 2026 at 04:10 AM

Toggle theme

Regarding For Simple Menus Using Do-while Loops In Java - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingRegarding For Simple Menus Using Do-while Loops In Java (333 Views)

1 Reply

Regarding For Simple Menus Using Do-while Loops In Java by Arjunkumar09(op): 6:53am On Feb 15, 2022
Hello All, I am trying to make a simple menu using a do-while loop in java. I have used this source to run the code and its looks like this:

 int choice;
Scanner scanChoice = new Scanner(System.in);
do {
System.out.println("Pick an option. 1 2 or 3."wink;
System.out.println("1. Apple"wink;
System.out.println("2. Pear"wink;
System.out.println("3. Pineapple"wink;

choice = scanChoice.nextInt();
} while (choice < 1 || choice > 3);

System.out.println("You picked " + choice);


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

Exception in thread "main" java.util.NoSuchElementException
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.

Anyone know how to fix this? Any suggestions?
Re: Regarding For Simple Menus Using Do-while Loops In Java by airsaylongcome: 10:24am On Feb 15, 2022
Try this
while ((choice < 1) || (choice > 3));
Re: Regarding For Simple Menus Using Do-while Loops In Java by islamics(m): 2:14pm On Feb 15, 2022
Arjunkumar09:
suggestions?
Your snippet run normal in my system ooo. Perhaps you should run it a local machine and see.
I tried it using same online compiler too but that site was too clumsy for me. Then I tried with other online compiler (programiz and ideone) and it works.
My thought is that, standard input maybe disabled for the online compiler. Hope the Scanner class was imported in your code?
1 Reply

What Is Loop? The Concept Of Loops In Programming| Coding For Kids | 5-9Tutorials On Having Deep Understanding About Loops In JS And How To IterateRegarding For DBMS Query!234

Mobile App UI Designer NeededHow To Create Excel Add-inHelp With This Configuration....