Search code examples
c#if-statementwhile-loopconditional-statementsboolean-expression

Else statement and while loop


Code skips the error if statements and goes straight to the else if

I need laps to go through and if its less than 2 then it'll go to the error and come back again to ask to enter a new value. vice versa for greater than 20. Im a new programmer and find C# Windows Forms hard to understand

        int.TryParse(txtNumberOfLaps.Text, out laps);

while (laps < 2 && laps > 20)
        {
            if (laps < 2)
            {
                MessageBox.Show("Laps can't be less than 2", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            else if (laps > 20)
            {
                MessageBox.Show("Laps can't be more than 20", "Error",
                MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            else if (laps > 2 && laps < 20)
            {
                break;
            }
        }
        
       
        
    

Solution

  • Which else if does it skip to? Your loop contains two. I imagine the program is exiting before even starting the loop due to the loop's sentinel value being insatiable. For any given integer n, 20>n<2 doesn't exist. It is literally impossible. You can see this by checking what number(s) would make each condition of your while loop true. For example

    n < 2 can most easily be satisfied by supplying a 1.

    n = 1 makes n > 20 false, however.

    on the other side, n > 20 is most easily made true by supplying 21 as an argument.

    n = 21 makes your first condition of n<2 false and thus your loop never begins

    So, in any case of n, your while loop never receives an initial True value to even begin.

    Now that that's settled, let's get you a solution! :)

    What you are looking for would be something like this:

    int.TryParse(txtNumberOfLaps.Text, out laps);
    
    while(true)
    {
       if (laps < 2 || laps > 20)
          {
             MessageBox.Show("Laps must be in range 2-20", "Error", 
             MessageBoxButtons.OK, MessageBoxIcon.Error);
             break;
          }
        else
          {
             // do other things 
             break;
          }
    }