简体   繁体   中英

Increment counter inside an array C#

I want to increment (using a counter) the value of a C# array. However I always get an error:

Index was outside the bounds of the array.

Here is my code.

while ((line = s.ReadLine()) != null)
{

    string[] parts = new string[40];
    parts=line.Split(' ');
    int a;
    for (a = 0; a <= (parts.Length - 1); a++)
    {

        if (parts[a] == "if")
        {
            node = node + 1;
            edge = edge + 1;
            int b = a + 2;
            Console.Write(parts[b]);
            if ((parts[a + 2]) == "{")
            {
                node = node + 1;
            } 
        }
    }
}

问题是当到达末尾时,aparts parts[a + 2]超出了数组的范围

Did you check that

parts[a + 2] doesn't exceed the array length?

One solution could be as follows:

while ((line = s.ReadLine()) != null)
{

    string[] parts = new string[40];
    parts=line.Split(' ');
    int a;
    for (a = 0; a <= (parts.Length - 1); a++)
    {

        if (parts[a] == "if")
        {
            node = node + 1;
            edge = edge + 1;
            int b = a + 2;
            Console.Write(parts[b]);
            if (((a + 2) < parts.length) && (parts[a + 2]) == "{")
            {
                node = node + 1;
            } 
        }
    }
}

In the code an extra check is put to see if a + 2 doesn't exceed the length of the parts-array. Then, the check is done, if the contents at array index a + 2 is equal to "{". If both conditions are true, then the code inside the block is evaluated.

If you use parts[a+2] you can only do the for loop until parts.Lenth -2:

while ((line = s.ReadLine()) != null)
{

    string[] parts = new string[40];
    parts=line.Split(' ');
    int a;
    for (a = 0; a <= (parts.Length - 2); a++)
    {

        if (parts[a] == "if")
        {
            node = node + 1;
            edge = edge + 1;
            int b = a + 2;
            Console.Write(parts[b]);
            if ((parts[a + 2]) == "{")
            {
                node = node + 1;
            } 
        }
    }
}

Your problem is here

int b = a + 2;
Console.Write(parts[b]); // here is the first problem
if ((parts[a + 2]) == "{") // why do a+2 here when you know parts[b] is the same thing (a +2)
{
      node = node + 1;
} 

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