2014-04-26 73 views
1

我想增加(使用计数器)C#数组的值。但是,我总是收到一个错误:数组中的增量计数器C#

索引超出了数组的范围。

这是我的代码。

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; 
      } 
     } 
    } 
} 
+0

在哪条线路?你调试了你的代码吗? http://ericlippert.com/2014/03/05/how-to-debug-small-programs/您可以通过调试轻松找到问题所在。 –

+0

它在这条线上吗? 'if((parts [a + 2])==“{”)'? – JoJo

+0

'new string [40]'是浪费时间和内存,因为下一个语句会分配一个新值。只需使用'var part = line.Split('');' –

回答

5

问题是parts[a + 2]当你达到年底+ 2超出数组边界的

1

你有没有检查

parts[a + 2]不超过数组的长度?

一种解决方案可以如下:

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; 
      } 
     } 
    } 
} 

在额外的检查被放置以查看是否+ 2不超过所述部件阵列的长度的代码。然后,如果数组索引a + 2处的内容等于“{”,则检查完成。如果两个条件都成立,那么块内的代码将被评估。

0

如果您使用的零件[A + 2]您只能循环做,直到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; 
      } 
     } 
    } 
} 
0

你的问题是在这里

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; 
}