Because your else
isn’t attached to anything. The if
without braces only encompasses the single statement that immediately follows it.
if (choice==5) { System.out.println("End of Game\n Thank you for playing with us!"); break; } else { System.out.println("Not a valid choice!\n Please try again...\n"); }
Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.
In addition, using a switch
here would make more sense.
int choice; boolean keepGoing = true; while(keepGoing) { System.out.println("---> Your choice: "); choice = input.nextInt(); switch(choice) { case 1: playGame(); break; case 2: loadGame(); break; // your other cases // ... case 5: System.out.println("End of Game\n Thank you for playing with us!"); keepGoing = false; break; default: System.out.println("Not a valid choice!\n Please try again...\n"); } }
Note that instead of an infinite for
loop I used a while(boolean)
, making it easy to exit the loop. Another approach would be using break with labels.