所以我在学校有这个项目,创建一个游戏"猜数字"。我正在尝试使用开关语句和while循环来循环对话sult。我尝试了很多可能性,但我进入了一个无限循环。只知道我是初学者。如果可能的话,我真的需要一些帮助。这是我的代码。提前谢谢。
<>之前private void btnStartTheGame_Click(对象发送者,EventArgs e){int guessthennumber = Convert.ToInt32(txtNumberGuess.Text);对话sult对话sult = MessageBox。Show("Is number" + number. tostring () + " you are thinking about ", "Answer the question ", messageboxbutton . yesno);开关(dialogResult){
case DialogResult.No:
while (dialogResult == DialogResult.No)
{
Random newNumberGenerator = new Random();
number = newNumberGenerator.Next(0, 101);
MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
}
break;
case DialogResult.Yes:
if (dialogResult == DialogResult.Yes)
{
MessageBox.Show("Congratulation! You guessed the number!!");
break;
}
break;
}
之前您需要加载对话框的新结果。
int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
DialogResult dialogResult;
do
{
Random newNumberGenerator = new Random();
number = newNumberGenerator.Next(0, 101);
dialogResult = MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
} while (dialogResult == DialogResult.No);
MessageBox.Show("Congratulation! You guessed the number!!");
do
循环将首先执行代码,然后检查条件。这也将防止在不同的地方有相同的代码,意思相同。