Reputation: 59
I'm only just beginning to learn to code in java and I've tried to figure this out for a while now, I've tried various methods and I've tried looking through similar questions but I can't find my answer.
I'm trying to get the loop to repeat while the user's input does not equal to 1, 2, or 3. Then stop repeating once a correct answer is entered.
// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules\n"
+ "2) Play the Game\n"
+ "3) Exit\n"
+ "Please enter your choice: (1 or 2 or 3) ";
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
// display the rules
String rules = "Rules:\n"
+ "The game will display total 3 multiple choice questions," +
" with 4 possible answers per question.\n"
+ "Once you answer the question, the correct answer will be displayed" +
" and the game will advance to the next question.\n"
+ "If you answer the question correctly, you will gain a point.\n"
+ "Each point is added to a total score that will be displayed at the" +
"end of the game.\n";
// declare an integer that reads the user input
int numericChoice = Integer.parseInt(userChoice);
boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);
while (true)
{
if (!valid) {
JOptionPane.showMessageDialog(null, "Invalid selection, please try again");
JOptionPane.showInputDialog(menu);
} if (valid){
break;
}
if (numericChoice == 1){
// display the rules then start the game
JOptionPane.showMessageDialog(null, rules);
}
else if (numericChoice == 2){
// start the game
JOptionPane.showMessageDialog(null, "Let's play the game.\n");
}
else if (numericChoice == 3)
// exit the game
System.exit(0);
Please help.
Upvotes: 1
Views: 200
Reputation: 140525
Your problem is that you are computing valid outside of your loop. In other words: you compute it once; before you enter the loop; and then, within your loop you never touch its value again.
Therefore, the "only" thing that your loop does is to raise that dialog over and over again.
Thus: you have to move all of those computations inside the loop!
So, not only
boolean valid = (numericChoice == 1 || numericChoice == 2 || numericChoice == 3);
needs to go into the loop, but also the code that fetches the user inputs, and determines numericChoice!
What you could do would be to write a helper method, like:
private int showMenuAndGetUserChoice() {
// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules\n" ...
String userChoice = JOptionPane.showInputDialog(menu);
JOptionPane.showMessageDialog(null, "You chose option " + userChoice); ...
return Integer.parseInt(userChoice);
}
And now you can loop much easier, by simply calling that method and checking its result within your loop body!
Upvotes: 1