此分配的目标是创建一个2D数组,然后返回数组中具有最大值的行。当我尝试在main方法中调用该方法时,我得到以下内容:
java.lang.ArrayIndexOutOfBoundsException:2
此时,我不知道该怎么办。
public class MDArray
{
private double[][] mdarray;
public MDArray(double[][] a)
{
mdarray = new double[a.length][];
for(int i = 0; i < a.length; i++)
{
mdarray[i] = new double[a[i].length];
for(int j= 0; j < a[i].length; j++)
{
mdarray[i][j] = a[i][j];
}
}
}
public double[] max()
{
double[] maxVal = new double[mdarray.length];
for(int i = 0, j = i + 1; i < maxVal.length; i++)
{
for(int k = 0; k < mdarray[i].length; k++)
{
if(mdarray[i][k] > mdarray[j][k])
{
maxVal = mdarray[i];
}
}
}
return maxVal;
}
}
答案 0 :(得分:1)
如果我理解你要做什么,我会从一个方法开始,以便从double[]
获得最大值
private static double getMaxValue(double[] a) {
int maxIndex = 0; // <-- start with the first
for (int i = 1; i < a.length; i++) { // <-- start with the second
if (a[i] > a[maxIndex]) {
maxIndex = i;
}
}
return a[maxIndex]; // <-- return the max value.
}
然后你可以使用它来确定具有最大值的row
(并复制数组),如
public double[] max() {
int maxIndex = 0; // <-- start with the first
for (int i = 1; i < mdarray.length; i++) { // <-- start with the second
double maxValue = getMaxValue(mdarray[maxIndex]);
double curValue = getMaxValue(mdarray[i]);
if (curValue > maxValue) {
maxIndex = i; // <-- The current value is greater, update the index.
}
}
return Arrays.copyOf(mdarray[maxIndex], mdarray[maxIndex].length);
}
最后,在构建MDArray
时,您还可以使用Arrays.copyOf
来简化逻辑,例如
public MDArray(double[][] a) {
mdarray = new double[a.length][];
for (int i = 0; i < a.length; i++) {
mdarray[i] = Arrays.copyOf(a[i], a[i].length);
}
}