How do I multiply columns of a 2D array? Java

1.4k views Asked by At

Previous methods construct and fill a 2D double array with a size defined by user input. computeCategoryAverages takes the middle indexes, averages them, then puts them in the final index computeOverallAverage is then supposed to multiply the 0 index (weight) by the final index and store that number, then repeat till the rows end, adding each time.

   Weight  Grade1  Grade2  Grade3  Average
  ----------------------------------------
1| 3.0  456.0  4356.0  456.0    1756.0  
2| 4.0  3456.0 674.0  34534.0  12888.0
3| 2.0  236.0  791.0   536.0    521.0

Example of what computeOverallAverage is supposed to do:
3.0 * 1756.0 = 5268
4 * 12888.0 = 51552
5268 + 51552= 56820
2 * 521= 1042
56820 + 1042 = 57862

computeCategoryAverages works flawlessly.

public static double[][] computeCategoryAverages(double[][] scoreArray){
    for(int i = 0; i < scoreArray.length; i++){
        double sum = 0;
        int numOfAssign = 0;
        double average=0.0;
        System.out.printf("The Average for category:%d:",i+1);
        System.out.println();
        for(int j = 1; j < scoreArray[i].length-1; j++){
            numOfAssign++;
            sum = sum + scoreArray[i][j];
        }
        average = sum / numOfAssign;
        scoreArray[i][scoreArray[i].length-1] = average;  
    }    
    return scoreArray;
}

The issues i'm having is with the computeOverallAverage, i'm not really sure how to make the arrays function properly with loops to multiply the columns and compound them with additiion.

// Compute the overall average
public static double computeOverallAverage(double[][] scoreArray){
    double currentAverage = 0;
    for(int i = 0; i < scoreArray[i].length-1; i++){
        //(weightedAverage = average *weight);
        double wAverage = scoreArray[i][scoreArray[i].length-1] * scoreArray[i][0];
        currentAverage += wAverage;

    }
    return currentAverage;
}
1

There are 1 answers

0
Ker p pag On

in your for loop in computeOverAllAverage

remote the index scoreArray[i].length

scoreArray.length = length of rows scoreArray[i].length = length of columns

in your for loop you want to loop for the rows.

 for(int i = 0; i < scoreArray.length-1; i++){
        //(weightedAverage = average *weight);
        double wAverage = scoreArray[i][scoreArray[i].length-1] * scoreArray[i][0];
        currentAverage += wAverage;

    }