0

如果我想让程序生成一个随机数,我该怎么办re-read/loopelse if statement直到找到一个类似的语句 if (button1.Text == ""),随机数只需要到 9。

这是我的代码,

    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?
                }

            }
4

3 回答 3

2
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 == "");
 }
于 2013-01-23T14:06:34.647 回答
1

if语句放在一个while()循环中。然后有一个执行break;语句以终止循环的条件:

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;
}
于 2013-01-23T14:08:32.123 回答
1
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
于 2013-01-23T14:09:23.030 回答