2011-11-26 94 views
-2

OK我試圖去通過代碼自己一堆次,但在人們的首選的Visual Studio總是說這是錯的..索引越界 - C#

指數成分股必然會錯誤

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //declare Arrays for buttons and 
      //LEDs 

      int[] buttonArray = new int[4]; // Left to right .-.. ------ 
      //left, top, bottom, right 
      int[,] ledArray = new int[10, 10]; 

      //declare variables 
      int strandSnake = 0; 
      int requestR = 0; 

      int countDeclareButtonArray = 0; 
      int countWriteButtonArray = 0; 



      //code 
      if (strandSnake != 1) 
      { 

      } 


      //Declaring the four buttons 
      for (int ip = 0; ip < 4; ip++) 
      { 
       buttonArray[countDeclareButtonArray] = countDeclareButtonArray; 
       countDeclareButtonArray++; 
      } 

      // writing the four buttons to the screen. 

      foreach (int ip in buttonArray) 
      { 

       requestR = buttonArray[countWriteButtonArray]; 
       countWriteButtonArray++; 
      } 

      Console.ReadLine(); 
     } 
    } 
} 
+3

請格式化您的代碼並提供更多信息。哪一行產生錯誤?你能把整個信息粘貼在這裏嗎? – gustavotkg

+1

錯誤發生在哪裏? – BWC

+0

「錯」是什麼意思? – JAM

回答

0

的你應該知道在C#中數組的索引範圍從0 .. array.Length - 1

所以,如果你有

int[] a = new int[4]; 

您可以訪問a [0]。一[1],A [2],[3]

但是,當你訪問一個[4],你會得到指數成分股必然會錯誤的。

調試和搜索哪裏錯誤從

0

去看看代碼片斷,countWriteButtonArray變量的值是4,所以你必須分配給0countWriteButtonArray

countWriteButtonArray=0; 
foreach (int ip in buttonArray) 
{ 
    requestR = buttonArray[countWriteButtonArray]; 
    countWriteButtonArray++; 
} 

如果你想從buttonArray數組中的元素,那麼你可以使用:

foreach (int ip in buttonArray) 
    { 
     // 
    } 

用於循環使用索引來遍歷數組。

for(countWriteButtonArray=0;countWriteButtonArray<=buttonArray.GetUpperBound(0);countWriteButtonArray++) 
    { 
     requestR = buttonArray[countWriteButtonArray]; 
    }