samedi 15 juin 2019

Random Bool in If-Else-If-Statement is not working

I have a small problem, but I just can't understand what is happening here.

I have a random bool generator:

public bool GetRandomBoolean()
{
   return new Random().Next(100) % 2 == 0;
}

And a function that is using this Random Bool Generator in a If-Else-If-Statement:

public void procedure()
{
   while (true)
   {
      if (GetRandomBoolean())
      {
          //this code runs
      }
      else if (GetRandomBoolean())
      {
          //this code is never executed
      }
   }
}

The else if-statement is never true and I cannot understand why.

If I try it this way:

public void procedure()
{
   while (true)
   {
      if (GetRandomBoolean())
      {
          //this code runs
      }
      else
      {
           if (GetRandomBoolean())
           {
              //this code never runs
           }
           else
           {
              //this code runs
           }
      }
   }
}

Can someone explain me, what is happening here? Shouldn't the Random Bool Generator return a new random bool every time I use it in an If-Statement?

Thank you for your time.




Aucun commentaire:

Enregistrer un commentaire