I'm stuck on a problem where I am supposed to make a method that returns the row with the highest average number in a 2D array
The method that I attached here only gets the averages of each row. I believe that I need to keep track the row with the highest average but I just don't know how Any suggestions?
int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
public static double getRowAverage(int grid[][]) {
int i, j;
double sum = 0, average = 0;
for (i = 0; i < grid.length; i ) {
for (j = 0; j < grid[i].length; j ) {
sum = sum grid[i][j];
}
average=sum/grid[i].length;
System.out.println("Average of row " (i 1) " = " average);
sum=0;
double a = i 1;
}
return average;
}
CodePudding user response:
You can compare and check if the row average is higher than the current highest
double rowAverage = sum / grid[i].length;
average = rowAverage > average ? rowAverage : average;
or even better, use Math.max
average = Math.max(average, sum / grid[i].length);
CodePudding user response:
Some notes regarding the code in your question.
- As well as
sum
, you also need to zeroaverage
for each new row. - No need to declare loop variables
i
andj
outside of the loop. - Java has "short-circuit" statements like
=
. - I understand that the purpose of this line:
double a = i 1;
is to store the index of the row (in the grid
) that contains the highest average. That variable should be int
(and not double
) since a row index can only be an int
. The variable should also be declared outside of the outer for
loop since you can only know its final value after you have processed all the rows in grid
. In the code below, I renamed a
to maxRow
.
- You need another variable to store the maximum.
public class Averages {
public static void main(String[] args) {
int[][] grid = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
double maxAvg = 0.0;
int maxRow = -1;
for (int i = 0; i < grid.length; i ) {
double sum = 0, average = 0;
for (int j = 0; j < grid[i].length; j ) {
sum = grid[i][j];
}
average = sum / grid[i].length;
if (average > maxAvg) {
maxAvg = average;
maxRow = i;
}
System.out.println("Average of row " (i 1) " = " average);
}
System.out.println("Row with highest average: " (maxRow 1));
}
}
When I run the above code, I get the following output:
Average of row 1 = 2.0
Average of row 2 = 5.0
Average of row 3 = 8.0
Row with highest average: 3