我有2个构造函数类,即Course和Student。学生班有测验分数和计算这些测验平均值的方法。课程课程具有学生的数组列表,我的目标是获取数组中所有学生的平均分数并计算平均分数,但是我不知道如何获取平均值(由学生类的平均方法得出)并在平均方法中使用它在课程中。
我试图在Student类中使另一个方法getAverage,然后在Course类中为每个学生在average方法中调用它。但这是不允许的,并且不确定是否可行。
public Student(String first, String last, Address home, Address school) {
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
}
public double average() {
avg = (test1 + test2 + test3) / 3.0;
return avg;
}
// Thats part of Student class
public Course(String name) {
courseName = name;
students = new ArrayList<Student>();
}
public boolean addStudent(Student person) {
if (!students.contains(person)) {
students.add(person);
return true;
}
return false;
}
public double average() { // Having trouble with creating this method
}
如果需要,我可以提供其他信息。提前致谢 ! 编辑:添加我尝试过的内容。
public double getAverage() {
return avg;
}
// GetAverage method in Student class
public double average() { // average method i tried in Course class
double average, studentAvg, sum;
studentAvg.getAverage(); // It isses error at this line
sum += studentAvg;
average = sum / students.size();
return average;
}
答案 0 :(得分:-2)
为了获得学生的总平均数, 需要迭代所有学生并计算总体平均水平。
Summation of All student average / number of students.
public double average() {
if (students.isEmpty()) {
return 0;
}
double sum = 0;
for (Student s: students) {
sum += s.average();
}
return sum/students.size();
}