2017-04-16 38 views
0

好吧,我試圖使用length屬性來搜索一個二維數組(我不得不使用這個本來我只是用對GetLength())。該數組隨機填充一定數量的行和列。它將要求用戶輸入一個數字進行搜索,然後搜索該數組並返回true或false,並在發現該數字時發回行和列的索引。搜索一個使用二維數組長度屬性

我從研究,我已經做了讓for循環設置正確的代碼相當有信心,但目前我收到寫着「數錯了[]內指數;預計2」的錯誤時我嘗試搜索數組的列。

我已經看了這個錯誤並從我發現這應該是正確的設置。所以,我不確定我的問題是在這個循環中,有人可以看看讓我知道我錯過了什麼步驟嗎?

謝謝!

int [,] math; 
math = new int[3, 5]; //So you can see my array that is declared in main 

static bool SearchArray(int search, int [,] array, out int row, out int coln) 
    { 
     row = -1; 
     coln = -1; 
     // search parameter is given from another method where it asks the user for a number to search for in the array. 

     for (int x = 0; x < array.Length; x++) 
     { 
      for (int y = 0; y < array[x].Length; y++) //error is here with the array[x] and continues to any reference I try to make similarly. 
      { 
       if (array[x][y] == search) 
       { 
        row = array[x]; 
        coln = array[y]; 
        return true; 
       } 
      } 
     } 
     return false 

回答

0

您正在混合鋸齒陣列與多維,實際上與二維陣列。兩個暗淡的解決方案。陣列將是這樣的:

static bool SearchArray(int search, int [,] array, out int row, out int coln) 
{ 
    row = -1; 
    coln = -1; 
    for (int x = 0; x < array.GetLength(0); x++) 
    { 
     for (int y = 0; y < array.GetLength(1); y++) 
     { 
      if (array[x,y] == search) 
      { 
       row = x; 
       coln = y; 
       return true; 
      } 
     } 
    } 
    return false 
} 
+0

只是爲了澄清,我必須使用對GetLength()來搜索,有沒有其他的選項可以使用,而不是對GetLength()? – ZLackLuster

+0

是的。 GetLength方法獲取選定排名的長度。 Length屬性只返回數組中的總項目大小。這是最精確的方法。 – DigheadsFerke

0

爲多維數組之間的差異的詳細信息請參見this question(如使用的是這裏)和交錯數組(數組的數組)。

如果要聲明多維數組,像這樣:

int [,] math = new int[3, 5]; 

必須訪問值這樣的:

int value = math[1,2]; 

如果聲明交錯數組,像這樣:

int[][] math = new int[3][]; 
math[0] = new int[5]; 
math[1] = new int[5]; 
math[2] = new int[5]; 

(雖然通常子陣列的大小會有所不同 - 因此鋸齒狀)。 那你訪問值:

int value = math[1][2]; 

爲了您的具體問題,如果使用多維數組,你還需要使用「Array.GetLength」,如:

for (int x = 0; x < array.GetLength(0); x++) 

得到零件的個別尺寸(如this question)。在你的榜樣「長度」是給你的大小的數組,第一維的不是長度。