Mert
Mert

Reputation: 17

while loop not repeating after setting to false

  boolean gotGoodGenInput = false;
  while (!gotGoodGenInput)
  {

    gotGoodGenInput = true;

    String inputGen = JOptionPane.showInputDialog
    (
      "Enter your Generation \n" +
      "It must be a number from 0 to 25"
    ); 

    if(inputGen != null)
    {  

      if (inputGen.isEmpty() || !inputGen.matches("[0-9]*")) 
      {
        JOptionPane.showMessageDialog
        (
          null,
          "Please input a number from 0 to 25",
          "Error",
          JOptionPane.ERROR_MESSAGE
        );
        gotGoodGenInput = false;
      }

      int GenNumber = Integer.parseInt(inputGen);

      if (GenNumber < 0 || GenNumber > 25)
      {
        JOptionPane.showMessageDialog
        (
          null,
          "Your number can't be less than 0 or greater than 25",
          "Error",
          JOptionPane.ERROR_MESSAGE
        );
        gotGoodGenInput = false;
      }

    }
    else
    {
      System.exit(0);
    }
  }

Hello the issue I am having is that if a user enters "a" (as an example) then they will get the error "please input a number from 0 to 25" from

 if (inputGen.isEmpty() || !inputGen.matches("[0-9]*"))

and it's supposed to restart the loop when it hits gotGoodGenInput = false;

but it keeps going to the next part where it will try to parse the int but of course it will error since "a" is not an int

so my issue is why is it not starting over when it reaches gotGoodGenInput = false; in the first if statement.

Upvotes: 0

Views: 1050

Answers (3)

yogaphil
yogaphil

Reputation: 91

Just setting gotGoodGenInput=false is not enough to restart the loop. You have changed the value of your variable, but you haven't told the program not to continue with the loop.

You probably want to add a continue; statement after each time you set gotGoodGenInput to false to get the behavior you describe.

You may also want to explore Swing's InputVerifiers. Check out this thread: Java Swing: Implementing a validity check of input values.

Upvotes: 2

Nicola Miotto
Nicola Miotto

Reputation: 3706

Looks like there is a missing else after the if statement where you check whether the string is empty or different from an integer. Like this it will enter the if statement, but then continue to the next one where it tries to parse the int.

Upvotes: 0

After the line

gotGoodGenInput = false;

add the line

continue;

which will restart from the beginning of the while loop.

Upvotes: 3

Related Questions