Heading Here

Hi there, I have been googling and been on youtube to find a solution. Now I need your help. I have a little problem that is bugging

    public partial class Form1 : Form
    {
        public Form1(){
        {
            InitializeComponent();
        }
        //declare the variables you will use in the randomizer above the code block
        private char[] letters = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
        private char secretLetter = ' ';  //I am not sure if this is correct????
        private char myGuess;
        private string GameResult;
        private void btnRandom_Click(object sender, EventArgs e)
        {
            Random rand = new Random();
            //the random number must have a range of numbers to choose from.
            int myRandomNumber = rand.Next(0, letters.Length - 1); 
            secretLetter = letters[myRandomNumber];
        }
        private void btnCheck_Click(object sender, EventArgs e)
        {
            //converting a string to a char
              myGuess = char.Parse(txtMessage.Text);             
            if (char.IsWhiteSpace(myGuess))
              {
                  MessageBox.Show("Please choose a letter between a and g!");
              }
              else
              {
                  if (secretLetter == myGuess)
                  {
                      MessageBox.Show("Congratulations, you guessed correctly");
                  }
                  else
                  {
                      GameResult = string.Format("Sorry your guess of {0} is incorrect, the secretLetter is {1}",
                      myGuess, secretLetter);
                      //secretLetter **s not recognized by my code******************
                  }
                 // MessageBox.Show(GameResult);   
              }
        }
    }
}

me. You need to first create a form with a Randomize button, a textbox and a Check button.
The question: when the user clicks on the randomize button, load a char arry with the letters a,b,c,d,e,f,g. The computer must then choose a random character from this array. Do not show the user the character yet. The user must enter their guess of what they think the character is into the textbox. Once the check button is checked, show the user a message stating whether the guess was correct or not.*****This is my code:*****************************

namespace Unit_3_Practical_Pretest_1

Dani AI

Generated

A concise expert addendum that fixes the two main issues already raised and hardens the flow for real use.

is correct about the random index: Random.Next's upper bound is exclusive. 's input-check idea is helpful, but the code needs a bit more robustness (avoid exceptions from char.Parse, handle uppercase input, and prevent reseeding Random on every click). The practical fixes below make the game reliable and safe for repeated plays.

Keep a single Random at class scope, track whether a secret is set (nullable char or a bool), validate the textbox so it contains exactly one non-whitespace character, and compare letters case-insensitively. Also assign the result string before showing the MessageBox and consider disabling the Randomize button until the round completes.

private readonly Random rng = new Random();
private readonly char[] pool = "abcdefg".ToCharArray();
private char? secret = null;

private void btnRandomize_Click(object sender, EventArgs e)
{
    secret = pool[rng.Next(pool.Length)];
    btnRandomize.Enabled = false;
    lblStatus.Text = "Secret chosen.";
}

private void btnCheck_Click(object sender, EventArgs e)
{
    var text = (txtMessage.Text ?? "").Trim();
    if (string.IsNullOrWhiteSpace(text) || text.Length != 1)
    {
        MessageBox.Show("Enter a single letter (a-g).");
        return;
    }
    if (!secret.HasValue)
    {
        MessageBox.Show("Click Randomize first.");
        return;
    }

    var guess = char.ToLowerInvariant(text[0]);
    var answer = char.ToLowerInvariant(secret.Value);
    var result = (guess == answer)
        ? "Congratulations — correct!"
        : $"Sorry, {guess} is incorrect; the secret was {secret}.";

    MessageBox.Show(result);
    secret = null;
    btnRandomize.Enabled = true;
    lblStatus.Text = "Ready.";
}

Extra tips: restrict allowed guesses to the a–g range (validate and reject other letters), consider handling KeyPress to prevent invalid input, and avoid recreating Random inside button handlers to prevent repeated identical seeds. This keeps the game predictable, safe from exceptions, and user-friendly.

Recommended Answers

All 2 Replies

Line 9 is correct.
Line 16 don't use Lenght-1, use Lenght. rand.Next will automatically have a range from 0 to Lenght-1

ddanbe said everything, just put your messagebox at line 39 to line 38 so it doesnt show two times when the letter is guessed. Just an advice if you want to put on line 29 instead of

if(char.IsWhiteSpace(myguess)) 

to

if (txtMessage.Text==" " || String.IsNullOrEmpty(txtMessage.Text))

and replace line 22 to line 28.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.