gpt4 book ai didi

Java 2D 数组 : Return Row with Maximum Value

转载 作者:行者123 更新时间:2023-11-30 07:00:22 25 4
gpt4 key购买 nike

此赋值的目标是创建一个二维数组,然后返回数组中具有最大值的行。当我尝试在主方法中调用该方法时,我得到以下信息:

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;
}
}

最佳答案

如果我明白你想要做什么,我会从一种从 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.
}

然后您可以使用它来确定具有最大值的(并复制数组),例如

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);
}
}

关于Java 2D 数组 : Return Row with Maximum Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41030053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com