2015-11-06 102 views
0

我試圖輸入二維數組並返回一個數組,代表數組數組。我得到一個數組越界的例外,我定義了int col變量。從二維數組中返回一列數組

當我在多分區陣列上運行它: {{1,3,8},{4,9,2},{6,11,14},{24,6,1}} 它返回[1,1,1,1]

public static int[] getColumn(int[][] grid, int j) { 
    int[] result = { 0 }; 
    int row = grid.length; 
    int col = grid[row -1].length; 

    for (int i = 0; i < col; i++) { 
     for (int p = 0; p < row; p++) { 
      if (j == i) { 
       int[] colJ = new int[row]; 
       for (int k = 0; k < row; k++) { 
        colJ[k] = grid[p][j]; 
       } 
       result = colJ; 
      } 

     } 

    } 
    return result; 
} 

回答

0

在Java數組中,索引從「0」開始。所以,你必須改變週期: for (int i = 1; i <= col; i++) {for (int i = 0; i < col; i++) {以及嵌套週期。例如,如果您有3X3矩陣,則左上角元素將具有索引[0] [0]和右下角元素[2] [2],但在實現時,您將在此獲得[3] [3]: grid[p][j]

這是我實現:

public static int[] getColumn(final int[][] grid, final int j) { 
    final int index = j - 1; // if we search for 1st element his index is 0, 2nd -> 1, etc. 
    final int[] result = new int[grid.length]; 
    for (int i = 0; i < grid.length; i++) { 
     result[i] = grid[i][index]; // take from each sub-array the index we're interesting in 
    } 
    return result; 
} 

輸出:{3, 9, 11, 6}電網{{1,3,8}, {4,9,2}, {6,11,14}, {24,6,1}}和j = 2

+0

我試着g返回第2列,所以我應該得到[3,9,11,6] – SM360

+0

不要添加2個答案。相反[編輯](http://stackoverflow.com/posts/33577433/edit)這個答案! – Frakcool

0

變化

int col = grid[row].length; 

int col = grid[row - 1].length;