我目前的方法工作得很好,但问题是它每次运行都会重置平均值,因此它会一遍又一遍地为第一个学生显示相同的结果。我试着用counter++;换到下一个学生,但还是不行。
public class resultsCalculator {
public static void main(String[] args) {
String[] classNames = {"Rick", "Tom", "Jill", "Megan"};
double[][] classResults = {
{100.0, 87.5, 95.3, 80.0},
{95.6, 25.0, 70.7, 85.0},
{95.3, 96.7, 82.6, 87.5},
{61.8, 55.9, 60.1, 60.6}
};
System.out.println("Class results: ");
processResults(classNames, classResults);
public static void processResults(String[] names, double[][] scores) {
for (int i = 0; i < names.length; i++) {
System.out.println("Student: " + names[i]);
System.out.print("\tAverage: ");
for (int j = 0; j < scores[i].length; j++) {
System.out.print(returnAverage(scores) + "\t");
}
}
}
public static double returnAverage (double scores[][]) {
double average = 0;
for (int l = 0; l < scores.length; l++) {
double sum = 0;
for (int j = 0; j < scores[l].length; j++) {
sum += scores[l][j];
average = sum / scores[l].length;
}
}
return average;
}
}
2条答案
按热度按时间ac1kyiln1#
我假设每一行都有一个学生的分数。如果是这样,就不需要嵌套循环来计算特定学生的平均值。请参见下面代码中的注解。
gorkyyrv2#
如果我理解正确的话,你需要整个二维阵列的平均值,对吗?所以,你需要把总数除以总计数。更多解释请参见注解。