2015-11-06 68 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;