So I have this project at school to create a game "Guess the number". I am trying to loop a DialogResult using a switch statement and a while loop. I tried many possibilities but I go into a infinite loop. Just to know I am a beginner.I would really need some help here if possible. This is my code. Thanks in advance.

private void btnStartTheGame_Click(object sender, EventArgs e)
        {
            int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
            DialogResult dialogResult = MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
            switch(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; }

有帮助吗?

解决方案

You need to load the new result of the dialog.

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!!");

The do loop will execute the code first, and then check the condition. THis will also prevent having the same piece of code at different places, meaning the same.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top