Home > Back-end >  How to keep showing the value of label again in form when the answer is not correct
How to keep showing the value of label again in form when the answer is not correct

Time:10-23

namespace Game
{
    public partial class Form2 : Form
    {
        String[] word = { "Ordinary", "Darkness", "Marriage" };
        Random rnd = new Random();

        public Form2()
        {
            InitializeComponent();
            label1.Text = word[rnd.Next(0, word.Length)];
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string guess;
            guess = textBox1.Text;

            while (guess != label1.Text)
            {
                if (guess != label1.Text)
                    MessageBox.Show("You got it right");
                else
                    MessageBox.Show("You got it wrong");
            }      
        }

When i type a wrong word which will drop to else, the form after that will not show the word on label. Im quite new to c# send help.

CodePudding user response:

First, this logic is incorrect:

if (guess != label1.Text)
{
    MessageBox.Show("You got it right");
}
else
    MessageBox.Show("You got it wrong");

The comparison operator should be ==. Otherwise it would be a very easy game (guessing literally any string which doesn't match the target string).

Once you correct that, consider what you're doing here:

while (guess != label1.Text)
{
    if (guess == label1.Text)
    {
        MessageBox.Show("You got it right");
    }
    else
        MessageBox.Show("You got it wrong");
}

So, if the guess is incorrect, what happens here? The loop continues, over and over, infinitely. So the program essentially "locks up" and becomes unresponsive because the logic is busy infinitely looping over a condition that never changes within that loop.

Taking a step back... Why do you even have this loop? All you want to do in this button click handler is check the answer, so just check the answer:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == label1.Text)
        MessageBox.Show("You got it right");
    else
        MessageBox.Show("You got it wrong");
}

No need for a loop at all because there's no operation to repeat. This logic will already be re-invoked any time the button is clicked.

CodePudding user response:

the whole while loop doesn't make much sense to me as the check seems a bit odd. Don't you want to check if the guess is equal to the label and if not show "you've got it wrong on the screen" and you don't really need the while around the whole thing.

        if (guess == label1.Text)
        {
            MessageBox.Show("You got it right"); 

        }
        else
        {
            MessageBox.Show("You got it wrong");
        }
  • Related