Search code examples
javajoptionpaneshowdialog

Using showInputDialog to get user input to quit program


I am trying to use showInputDialog to get the user to enter N or n when they want to quit the program. I'm using a do-while loop and I think my logic is wrong. When I enter N or n the program just continues to run through the loop.

Below is my code:

public static void main(String args[]) {
    MyClass app = new MyClass();
    String quit;
    // get user input until they quit
    do {

        boolean validEntry1 = false;
        do {
            String userEntry;
            double num1;
            // check for valid numerical entry and catch invalid entries
            try {
                userEntry = JOptionPane
                        .showInputDialog("Enter number 1");
                num1 = Double.parseDouble(userEntry);
                app.setNumberOne(num1);
                validEntry1 = true;

            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null,
                        "Please enter a valid number");
            }
        } while (!validEntry1);

        // gets user input for number 2
        boolean validEntry2 = false;
        do {
            String userEntry1;
            double num2;
            // check for valid numerical input for num2
            try {
                userEntry1 = JOptionPane
                        .showInputDialog("Enter number 2");
                num2 = Double.parseDouble(userEntry1);
                app.setNumberTwo(num2);
                validEntry2 = true;
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(null,
                        "Please enter a valid number");
            }
        } while (!validEntry2);

         //this method gives the result of a multiplying num1 and num2
         app.output();

        // prompt user to continue
        quit = JOptionPane
                .showInputDialog("Enter N or n to quit. Enter any other key to continue.");

    } while (quit != "N" || quit != "n"); //this is where I am having issues, It continues to loop regardless of what I enter.
}// end of main

Any suggestions on where I am going wrong?

Is there a better way to get user input to quit in the gui?


Solution

  • quit is a String you should compare using .equalsIgnoreCase().

    Try like this:

    while (!quit.equalsIgnoreCase("n"));
    

    Strings are objects so they use the equals method for comparison or in this case you can use equalsIgnoreCase for both cases.