user7218814
user7218814

Reputation:

Java 2D Array: Return Row with Maximum Value

The goal of this assignment is to create a 2D array and then return the row with the maximum value in the array. When I try to call the method in the main method, I get the following:

java.lang.ArrayIndexOutOfBoundsException: 2

At this point, I'm not sure how to proceed.

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

Upvotes: 1

Views: 94

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201419

If I understand what you are trying to do, I would start with a method to get the maximum value from a double[] like

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

Then you can use that to determine the row with the maximum value (and copy the array) like

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

Finally, when constructing your MDArray you could also use Arrays.copyOf to simplify the logic like

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

Upvotes: 1

Related Questions