Glen Hunter
Glen Hunter

Reputation: 65

create a random loop until a statement is true

What should I do if I wanted the program to generate a random number then re-read/loop the else if statement until it finds a statement that is similar to this if (button1.Text == ""), The random number only needs to go up to 9.

This is my code,

    private void button1_Click(object sender, EventArgs e)
    {
          var rc = new Random();
          storeRI = rc.Next(1, 9);

            if (storeRI == 1)
            {
                if (button1.Text == "")
                {
                    button1.Text = "X";
                }
                else
                {
                   //Need to generate another random number
                    //And read the else if statement again... how?
                }

            }

            else if (storeRI == 2)
            {
                if (button1.Text == "")
                {
                    button1.Text = "X";
                }
                else
                {
                   //Need to generate another random number
                    //And read the else if statement again... how?
                }

            }

Upvotes: 0

Views: 1397

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

var rc = new Random();
int[] numbers = { 1, 2 }; // numbers from your if..else blocks

do {
  storeRI = rc.Next(1, 9);

  if (!numbers.Contains(storeRI))
      break; // not matched any if..else block

  if (button1.Text == "")
  {
      button1.Text = "X";
      break; // set text and break loop
  }

} while(true); // generate new number and do check again

Upvotes: 1

D Stanley
D Stanley

Reputation: 152624

put the if statements in a while() loop. Then have a contidion that executes a break; statement to terminate the loop:

while(button1.Text == "")
{
    if (storeRI == 1)
    {
        if (button1.Text == "")
        {
            button1.Text = "X";
        }
        else
        {
             //Need to generate another random number
             storeRI = rc.Next(1, 9);
        }

    }

    else if (storeRI == 2)
    {
     ...
    }
    else
        break;
}

Upvotes: 1

Vincent James
Vincent James

Reputation: 1158

private void button1_Click(object sender, EventArgs e)
{
      var rc = new Random();
      do
      {
        storeRI = rc.Next(1, 9);

        if (storeRI == 1)
        {
            if (button1.Text == "")
            {
                button1.Text = "X";
            }
        }

        else if (storeRI == 2)
        {
            if (button1.Text == "")
            {
                button1.Text = "X";
            }
        }
      } while (button1.Text == "");
 }

Upvotes: 2

Related Questions