创建一个随机循环,直到语句为 true
本文关键字:语句 true 循环 随机 一个 创建 | 更新日期: 2023-09-27 17:55:17
如果我想让程序生成一个随机数然后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?
}
}
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 == "");
}
将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;
}
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