2014-04-26 72 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; 
}