谁能告诉我如何计算一个类(class)学生所有对象的平均成绩?
我类的学生包含:
String name // of student
String [] courses // the array that contains all the courses for each student
Int [] grades // the array that contains the grades for each student
我已经创建了一个计算单个对象(学生)平均值的方法:
public double averageGradeStud() {
double total = 0;
for (int i = 0; i < numberOfGrades; i++) {
total += grades[i];
}
return (total / numberOfGrades);
但是我如何创建一个方法来计算已创建的所有学生(对象)的平均成绩?
最佳答案
我假设学生在一个集合中。您需要遍历集合并将计算学生平均成绩的函数映射到每个学生。同时将这些值相加,在迭代完成后,将其除以学生人数:
List<Student> students;
double total = 0;
for(Student s : students){
total += s.averageGradeStud();
}
double averageForAll = total / students.size();
关于java - 计算一个类的 x 个对象的平均成绩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418377/