문제

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