从2D Array Java创建一维数组

时间:2018-03-16 18:42:26

标签: java arrays multidimensional-array

我正在尝试编写一个采用2D数组参数的方法,并从中创建一个长度等于原始数组中行数的一维数组。我还希望新数组的行中的元素等于原始数组的每一行的最小值。如果原始行为空,我希望新数组等于0.0。我在下面编写了我的方法,但是我收到了indexOutOfBounds错误,我不知道为什么......感谢

enter  public double[] newOneD(double[][] x) {
int xrow = x.length;
int xcol = x[0].length;
double[] y = new double[xrow];  
int min = 0;
for (int i = 0; i < xrow; i++){ 
    for (int j = 0; j < xcol; j++) {
        if(x[i][j] < x[i][min]) {min = j;}
        y[i] = x[i][min];}
}
return y;}

1 个答案:

答案 0 :(得分:1)

您的错误是由于您假设每行中列的数量等于第一行中的列数:

int xcol = x[0].length; //this is an assumption that doesn't hold true

如果你真的必须使用数组,那么你可以遍历所有行并找出你必须使用的长度:

int xcol = 0;
for(int i = 0; i < xrow; i++) {
    xcol = Math.max(xcol, x[i].length);
}

使用此新xcol值,您的代码可以继续。

您也可以考虑使用灵活的数据结构,例如数组列表。

相关问题