如果我希望程序生成一个随机数,然后re-read/loop
else if statement
,直到找到与(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?
}
}
答案 0 :(得分: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 == "");
}
答案 1 :(得分: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;
}
答案 2 :(得分: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