谁能给我一个关于如何计算一个班级学生所有对象的平均分数的线索?
我的班级学生包含:
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);但是,我如何创建一个方法来计算已经创建的所有学生(对象)的平均成绩呢?
发布于 2015-05-24 07:02:48
我假设学生在一个集合中。您需要遍历集合,并将计算学生平均成绩的函数映射到每个学生。同时将这些值相加,并在迭代完成后,将其除以学生数量:
List<Student> students;
double total = 0;
for(Student s : students){
total += s.averageGradeStud();
}
double averageForAll = total / students.size();发布于 2015-05-24 07:06:58
我会说,最简洁的方法是对你的学生做一个ArrayList,然后做一个方法,得到他们的总成绩平均值。然后,您可以使用for循环来计算所有学生的总数。
//Example
int totalGrad = 0;
for(int i = 0; i < studentList.size(); i++)
{
totalGrad += studentList.get(i).getAverageGrade();
// if you want to then average the totalGrad you can do the following
totalGrad = (totalGrad / studentList.size());
}https://stackoverflow.com/questions/30418377
复制相似问题