0

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

napi15
  • 2,354
  • 2
  • 31
  • 55

2 Answers2

3

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().

Community
  • 1
  • 1
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

The proper way of writing it :

 if(txt!=null &&txt!="0" )
{
 if (number <= 1 || number > 12) {
   JOptionPane.showMessageDialog(null, "Integer must be between 1 and 12");
 else
  number = Integer.parseInt(txt);
}
else ///He hit calcel
condition= true 
napi15
  • 2,354
  • 2
  • 31
  • 55