2016-12-14 105 views
-2

我想要生成5組座標(只是兩個整數在一起)但是我得到錯誤「索引超出了數組錯誤的界限」。任何幫助,將不勝感激。C#數組:索引超出了數組錯誤的界限

private void BtnAGenerate_Click(object sender, EventArgs e) 
    { 
     int TotalCoordinates = 0; 

     int[,] GenaratedCoordinates = new int[4, 1]; 
     while (TotalCoordinates <5) 
     { 
      Random rnd = new Random(); 
      int RandomNumberX = rnd.Next(1, 5); // creates a number between 1 and 5 
      int RandomNumberY = rnd.Next(1, 10); // creates a number between 1 and 10 

      GenaratedCoordinates[TotalCoordinates, 0] = RandomNumberX; 
      GenaratedCoordinates[TotalCoordinates, 1] = RandomNumberY; 
      TotalCoordinates++;    
     } 

    } 
+5

對於第二個索引,只有一個項目在索引0處,但您正在訪問索引1. – clcto

+6

第一個插槽(0-3索引)中只有4個項目,但您將訪問插槽4 – ps2goat

+0

'int [,] GenaratedCoordinates = new int [5,2]'。 VB具有其他功能,其中數組長度從零開始,因此vb中的「int(4,1)」在第一個槽中實際上具有5的長度,而第二個中的長度爲2。 https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx – ps2goat

回答

1

當您創建一個數組或多維數組時,給定的值就是元素的數量。然而,指數從0開始,所以如果你有new int[3],可能的指標爲0120通過n-1對於一般情況new int[ n ])。所以,當你使用:

int[,] GenaratedCoordinates = new int[4, 1]; 

可用的指標是

GenaratedCoordinates[0, 0] 
GenaratedCoordinates[1, 0] 
GenaratedCoordinates[2, 0] 
GenaratedCoordinates[3, 0] 

但是你訪問GeneralCoordinates[0,1],例如,這是無效的,將拋出您所看到的異常。好像你要代表5點的數組,所以你需要:

int[,] GenaratedCoordinates = new int[5, 2]; // 5 points with an x and y coordinate each 

甚至更​​好,表達你想要的東西更清楚地使用已經可以抽象或您自己創建。在這種情況下,已經有一個System.Drawing.Point struct可以用來表示一個點。因此可以有這些結構的代替隱蔽多維陣列的陣列,當第二索引具有其中0表示x和1爲Y的含義:

System.Drawing.Point[] GeneratedCoordinates = new System.Drawing.Point[5]; 

,然後使用訪問它們,例如:

GeneratedCoordinates[ TotalCoordinates ].X = RandomNumberX; 
GeneratedCoordinates[ TotalCoordinates ].Y = RandomNumberY;