hangman game error. out of range error

Jonny123

Member
Joined
Oct 2, 2015
Messages
13
Programming Experience
Beginner
Hello,
I am getting an error message on the C# hangman program that i'm trying to recreate from a YouTube video at:
https://www.youtube.com/watch?v=E8XQ9x-7yYk
the program seems to run fairly well, but runs into an error once in a while. I'm not sure what code is needed to display the problem that I am having. Below is the section in which the error message shows.

            if (word.Contains(letter))
            {
                char[] letters = word.ToCharArray();
                for (int i = 0; i < letters.Length; i++)
                {
                    if (letters == letter)
                        labels.Text = letter.ToString(); // <-------------------- this creates an out of range error
                }
                foreach (Label l in labels)
                    if (l.Text == "_") return;
                MessageBox.Show("You have won", "Congrats");
                ResetGame();
            }
 
Noone wants to see all the code. What we want to see is the relevant code. I've told you numerous times that the issue is that you're not creating and populating the array of Labels properly. Obviously, where you are creating and populating the array of Labels is the relevant code.
 
Here is the MakeLables function.

C#:
void MakeLables()
        {
            word = GetRandomWord();
            char[] chars = word.ToCharArray();
            int between = 330 / chars.Length - 1;
            for (int i = 0; i < chars.Length - 1; i++)
            {
                labels.Add(new Label());
                labels[i].Location = new Point((i * between) + 10, 80);
                labels[i].Text = "_";
                labels[i].Parent = groupBox2;
                labels[i].BringToFront();
                labels[i].CreateControl();
            }
            label1.Text = "Word Length: " + (chars.Length - 1).ToString();
        }
 
On the face of it, that looks OK. I suggest that you debug your code. Step through that method and make sure that `labels` is populated the way you expect and then debug the section that's generating the exception and make sure that `labels` is still populated the way you expect. I can't see anything obvious just by reading the code, which is exactly why it's important to debug and actually watch the code in action.
 
One thing i notice is that "MakeLabels" is misspelled. When the module is called it is misspelled also. I'm not sure if that effect anything.

C#:
void MakeLables()
 
Back
Top Bottom