Armando Frias Armando Frias - 2 months ago 12
Java Question

Need to exit a loop once the correct input is entered

Please see my code below for a quiz game. I have been trying to figure out for 2 days now how to correctly code the loop at the option menu. Once I know how to code it correctly I would be able to code in the rest of the loops I need for the other questions.

The way I have it coded right now it gets stuck on "Invalid selection, please try again." infinitely.

Someone please help me with the correct code. :(

Everything I've been able to find related to this utilizes Scanner input instead of the JOptionPane.

package team1;

//this is required for JOptionPane to work
import javax.swing.JOptionPane;

//this allows for exception throwing
import java.io.*;

public class GameV2 {

public static void main(String[] args) throws IOException {

/**
* Version 2 Updates:
* - added 2 more sets of questions and answers
* - created a decision structure to determine the path of the game based on +
the user's menu choice
* - created a decision structure to indicate whether to the user whether an +
answer is correct or incorrect.
* - added point values to each question and a totalScore accumulator which +
displays at the end of the game.
*/

// display an introduction to the game.
JOptionPane.showMessageDialog(null, "Welcome to Team 1's Game Version 2!");

// prompt the user for his/her first name
String firstname;
firstname = JOptionPane.showInputDialog("What is your first name?");

// prompt the user for his/her last name
String lastname;
lastname = JOptionPane.showInputDialog("What is your last name?");

// display a customized hello message to the user
JOptionPane.showMessageDialog(null, "Hi, " + firstname + " " + lastname + "!");

**// create a menu and display it to the user
// then ask the user to choose an option
String menu = "1) See Rules and Play the Game\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);

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);
}
while (!valid){
JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
JOptionPane.showInputDialog(menu);
continue;
}

Answer

To make your implementation work like you intend to you should rewrite your loop, e.g. like the following:

    boolean valid = false;
    do {
        final String userChoice = JOptionPane.showInputDialog(menu);
        final int numericChoice = Integer.parseInt(userChoice);
        JOptionPane.showMessageDialog(null, "You chose option " + userChoice);
        if (numericChoice == 1) {
            valid = true;
            // display the rules then start the game
            JOptionPane.showMessageDialog(null, rules);
        } else if (numericChoice == 2) {
            valid = true;
            // start the game
            JOptionPane.showMessageDialog(null, "Let's play the game.\n");
        } else if (numericChoice == 3) {
            valid = true;
            // exit the game
            System.exit(0);
        } else {
            JOptionPane.showMessageDialog(null, "Ivalid selection, please try again");
        }
    } while (!valid);

You should also remove the lines

    String userChoice = JOptionPane.showInputDialog(menu);

    JOptionPane.showMessageDialog(null, "You chose option " + userChoice); 

before the loop because they will be executed inside of it.

If you do it like that than your loop has the following cycle:

  1. Get and store user input (userChoice and numericChoice*)
  2. Show user their input
  3. Handle input
    • if 1 or 2 or 3 set valid to true and continue according to choice
      or
    • Show an error and repeat from step 1

* You should think about handling the case when userChoice can not be parsed into a number