2011-10-20 22 views
2

我覺得自己像一個白癡問這個問題,但我不能爲我的生活找出爲什麼這個IndexOutOfRangeException發生。 (我的意思是,我知道爲什麼它的發生,我只是不知道什麼是無效的關於我的代碼)檢查的代碼下面被拋出錯誤的位置:爲什麼這個int數組拋出IndexOutOfRangeException?

public int[, ,] FindTablePairings(System.Text.RegularExpressions.MatchCollection mcBegin, System.Text.RegularExpressions.MatchCollection mcEnd) 
    { 
     int[,,] intTablePairs = new int[mcBegin.Count, 1, 1]; 
     int[] intBegin = new int[mcBegin.Count]; 
     int[] intEnd = new int[mcBegin.Count]; 

     for (int q = 0; q < mcBegin.Count; q++) 
     { 
      intBegin[q] = mcBegin[q].Index; 
     } 
     for (int q = 0; q < mcEnd.Count; q++) 
     { 
      intEnd[q] = mcEnd[q].Index; 
     } 

     int intBeginCount = mcBegin.Count; 
     int intEndCount = mcEnd.Count; 
     int i = 0; 
     int j = 0; 
     int k = 0; 

     while (i < intBeginCount) 
     { 
      j = i; 
      while (j < intEndCount) 
      { 
       if (intBegin[i + 1] < intEnd[j]) 
       { 
        j++; 
       } 
       else 
       { 
        intTablePairs[i, 0, 0] = intBegin[i]; 
        intTablePairs[i, 1, 0] = intEnd[j]; 
        intEnd[j] = -1;       //EXCEPTION OCCURS HERE 
        break; 
       } 
      } 
      if (j == intEndCount) 
      { 
       intTablePairs[i, 0, 0] = intBegin[i]; 
       intTablePairs[i, 1, 0] = intEnd[j - 1]; 
       intEndCount--; 
      } 

      while (k < intEndCount) 
      { 
       if (intEnd[k] == -1) 
       { 
        k++; 
       } 
       else 
       { 
        intTablePairs[i,0,0] = intBegin[i]; 
        intTablePairs[i,1,0] = intEnd[k]; 
        intEnd[k] = -1; 
        k=0; 
        break; 
       } 
      } 
     } 

     return intTablePairs; 
    } 

的代碼只盯着起始標籤和結束標籤出現的字符索引。沒有什麼超級複雜的......但最糟糕的是在intEnd[j] = -1;和調試器中引發異常,在執行該語句之前,所有數組和MatchCollections都已正確初始化並填充,包括intEnd[]!我已經調試過,以確保數組存在並已初始化,並且我還清理了解決方案並重建了它。

有人對這裏發生了什麼有什麼建議?

回答

5

我相信錯誤實際上是在這條線

intTablePairs[i, 1, 0] = intEnd[j]; 

這裏的問題是,你已經在intTablePairs定義的最後2個維度的這兩個長度爲1。因此使用索引1是無效的,因爲它等於長度。好像你的意思是定義範圍爲

int[,,] intTablePairs = new int[mcBegin.Count, 2, 2]; 
+0

看來'intEnd [j] = -1'行出現錯誤。 –

+1

@ AS-CII不能是一個錯誤,但直接在它上面的行也會出錯。都訪問'intEnd [j]'。 – JaredPar

+0

我沒有寫出你的解決方案是錯誤的;)我認爲他錯誤地將他的代碼複製到StackOverflow中。 –

0

也許看看這個:

int[] intEnd = new int[mcBegin.Count]; 

更換mcBegin上mcEnd和嘗試。

0

我想intEnd應該mcEnd.Count能力來設定。因此,而不是:

int[] intEnd = new int[mcBegin.Count]; 

你應該有:

int[] intEnd = new int[mcEnd.Count]; 

希望它能幫助。

相關問題