A 2D array in Java is an array of references to 1D arrays, each of which represents a row. See Intro to 2D arrays for additional discussion.
getAverage
method
The getAverage
method finds the average (mean) of the elements in a 1D array.
public static double getAverage(int[] vals)
{
int sum = 0;
for(int i = 0; i < vals.length; i++)
sum += vals[i];
return sum / (double) vals.length;
}
findHighestAverage
method
The findHighestAverage
method accepts the 2D array scores
as a parameter. Each row in scores
contains the scores for 1 student. findHighestAverage
returns the average of the highest scoring student. The method assumes that scores
has at least 1 row.
See Finding the minimum or maximum for a discussion of the algorithm used to find the max.
public static double findHighestAverage(int[][] scores)
{
double highestAverage = getAverage(scores[0]);
for(int r = 1; r < scores.length; r++)
{
double average = getAverage(scores[r]);
if(average > highestAverage)
highestAverage = average;
}
return highestAverage;
}
scores[0]
stores a reference to the 1D array representing the first row in scores
. The call getAverage(scores[0])
passes the reference to the first row to getAverage
. getAverage
returns the average of the values in the first row.
scores[r]
stores a reference to the row at index r
in scores
. The call getAverage(scores[r])
works the same as the call getAverage(scores[0])
.
main
method
public static void main(String[] args)
{
int[] nums = new int[] {5, 6, 7};
System.out.println(getAverage(nums)); // 6.0
int[][] scores = new int[][] {
{90, 75, 80, 85}, // 82.5
{85, 90, 90, 90}, // 88.75
{90, 95, 95, 100}, // 95
{70, 70, 90, 60} // 72.5
};
System.out.println(findHighestAverage(scores)); // 95.0
}
The getAverage
method accepts a 1D array as a parameter. From the perspective of getAverage
, a row from a 2D array is the same as a 1D array that is not part of a 2D array.
The call getAverage(nums)
passes a reference to the 1D array containing [5, 6, 7]
to getAverage
, which computes and returns the average (6.0
).