import java.util.HashMap; import java.util.Map; public class Gradebook { /** * Course -> Student -> Score. */ private final Map> grades; /** * Gradebook constructor. */ public Gradebook() { this.grades = new HashMap<>(10); } /** * Gets the average score for a given course. If the course can not be * found, -1 is returned. * * @param course the course * @return the average score, -1 if the course does not exist */ public double getAverageScore(String course) { double result = 0.0; Map courseGrades = this.grades.get(course); if (courseGrades == null) { return -1.0; } int count = courseGrades.values().size(); for (double score : courseGrades.values()) { result += score; } return (count == 0) ? 0.0 : (result / (double) count); } /** * Gets the average score for a given student (across all courses). If the * student can not be found in any course, -1 is returned. * * @param student the student * @return the average score, -1 if the student isn't found in any course */ public double getAverageScore(Student student) { double result = 0.0; int count = 0; for (Map studentGrades : this.grades.values()) { Double studentScore = studentGrades.get(student); if (studentScore != null) { result += studentScore; count += 1; } } return (count == 0) ? -1.0 : (result / (double) count); } /** * Gets the score for a given course, for a given student. If the course or * the student does not exist, -1 is returned. * * @param course the course name * @param student the student * @return the score, -1 if not found */ public double getScore(String course, Student student) { Map courseGrades = this.grades.get(course); if (courseGrades != null) { Double studentGrade = courseGrades.get(student); if (studentGrade != null) { return studentGrade; } } return -1.0; } /** * Sets the score for a given student, for a given course. If the course or * the student would not exist, they are created. If the student already * has a score for this course, the previous score will be discarded and * overwritten. * * @param course the course name * @param student the student * @param score the score to set */ public void setScore(String course, Student student, double score) { Map scores = this.grades.get(course); if (scores == null) { scores = new HashMap<>(10); } scores.put(student, score); this.grades.put(course, scores); } }