简体   繁体   中英

C# runtime error: index out of range

I have to make a simple windows forms application in which the player takes turns with the computer in taking sticks (which I made out of labels which go invisible), but I am having a problem with the code for the pc as it causes a runtime error "index out of range", and I can't figure it out..

    private void pcTake(int x)
    {
        textBox1.Text = "I take " + x;
        for (int i = 0; i < labels.Count; i++)
        {
            if (labels[i].Visible == false && labels[i + 1].Visible == true)
            {
                while (x > 0)
                {
                    if (x + i > labels.Count)
                        break;
                    labels[i + x].Visible = false;
                    x--;
                }
                break;
            }
        }

    }

x is a random number, labels is a list containing the labels

foreach (Control c in this.Controls)
        {
            if (c is Label)
            {
                labels.Add(c);
                c.Enabled = true;
            }
        }

thanks in advance

You are getting the exception beause of your comparison

labels[i + 1].Visible == true

since your loop is based on < labels.Count , that means when the loop index reaches to count - 1 , your condition is suppose to check array index on count (because of i + 1 ), since array's index is 0 based, you are getting the exception.

If you want to check the current index and later index then your loop condition should be i < labels.Count - 1 like:

for (int i = 0; i < labels.Count - 1; i++)

In C#, arrays are 0-indexed, so the last item is labels[labels.Count-1]; you should change this

if (x + i > labels.Count)
    break;

into this

if (x + i > labels.Count -1)
    break;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM