简体   繁体   中英

How can i take method result from other class?

I have 2 constructor classes, Course and Student. Student class have test scores and method that computes average of those tests. Course class have array list of Students, and my goal is to take average scores of all Students in array and compute average score, but i dont understand how to take avg value(result from average method from Student class) and use it in average method in Course class.

I tried to make another method getAverage in Student class, and then call it in average method in Course class, for each student. But thats not allowed, and not sure if that would work.

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

}

I can provide additional info if needed. Thanks in advance ! EDIT: Adding what i tried.

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;

 }

In order to get total average of Students, Need to iterate all the students and calculate overall average.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM