0

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?

Mac
  • 375
  • 6
  • 10
  • 17
  • quit != "N"is not how String comparison is done in Java. Why not use a JOptionPane.showOptionDialog and use custom buttons? – MadProgrammer Jan 23 '15 at 20:43
  • It's an assignment and my professor wants the user to enter they're selection. – Mac Jan 25 '15 at 14:22

1 Answers1

0

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.

brso05
  • 13,142
  • 2
  • 21
  • 40