Question:
In a math class, the teacher wants to use a method to calculate the average test score for the students. Create a Java method called calculateAverage that takes an array of test scores as input and returns the average score as a double. The method signature should be:
public static double calculateAverage(int[] scores)
Use the method calculateAverage in a main method to calculate and print the average of the following student test scores: 85, 92, 78, 88, and 90.
Answer:
public class MathClassMethods {
public static double calculateAverage(int[] scores) {
int sum = 0;
for (int score : scores) {
sum += score;
}
return (double) sum / scores.length;
}
public static void main(String[] args) {
int[] testScores = {85, 92, 78, 88, 90};
double averageScore = calculateAverage(testScores);
System.out.println("The average test score is: " + averageScore);
}
}
Explanation:
calculateAverage method, we use a for-each loop to iterate through the scores array and calculate the sum of all the test scores.double by dividing the sum by the number of scores in the array.main method, an array testScores containing the test scores is created.calculateAverage method is called with the testScores array as an argument, and the result is stored in the averageScore variable.