Search code examples
javajoptionpane

How to not confuse between 0 and cancel buttom JoptionPane


I'm trying to make loop as to validate a user imput in java

the user must enter integer between 1 and 12 but if click cancel the JoptionPane Must close

   int number = 0;
     boolean condition= false;

   while (!condition) {
        try {
            txt = JOptionPane.showInputDialog(null,
                    "Entrez num :", "Number",
                    JOptionPane.PLAIN_MESSAGE);

            if(txt!=null &&txt!="0" )
            number = Integer.parseInt(txt);

                      if (number <= 1 || number > 12) {
            JOptionPane.showMessageDialog(null, "Integer must be between 1 and 12");
        }else 
              condition=true;

        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "you have to enter an integer");
        }

   }

The problem I'm facing is when the user click on cancel this condition is popping , but I want the Joption pane to close and return to main menu

JOptionPane.showMessageDialog(null, "Integer must be between 1 and 12");

how to not confuse between when the user enter 0 in the box and when he click cancel ?

Much Appreciation,

Bass


Solution

  • What does the javadoc say?

    It says:

    Returns: user's input, or null meaning the user canceled the input.

    So if you get "0", the user entered 0, and if you get null, the user cancelled.

    Side note: don't use == to compare strings. Use equals().