Let's Think This Through
In this part, we'll extend the Student class from Part 1 with a core feature. We'll use the HashMap to store subject-score pairs, then loop through values() to calculate the average. We'll write a method that uses an if-else chain to determine the grade letter (A, B, C, F) based on the average score. This is also good practice for the pattern of a method returning a value.
Let's Build It
Add an addScore(String subject, int score) method to the Student class using subjectScores.put(). Write a calculateAverage() method that loops through subjectScores.values(), sums the total, divides by the size, and returns the average as a double (return 0 if the map is empty). In getGrade(), check the result of calculateAverage() with if-else conditions (>=90 for A, >=75 for B, >=50 for C, otherwise F) and return the grade as a String. In the main method, add 3 subject scores for a student and print out their average and grade.
Sample Code
class Student {
private String name;
private int id;
private HashMap<String, Integer> subjectScores;
public Student(String name, int id) {
this.name = name;
this.id = id;
this.subjectScores = new HashMap<>();
}
public void addScore(String subject, int score) {
subjectScores.put(subject, score);
}
public double calculateAverage() {
int total = 0;
for (int score : subjectScores.values()) {
total += score;
}
return subjectScores.isEmpty() ? 0 : (double) total / subjectScores.size();
}
public String getGrade() {
double avg = calculateAverage();
if (avg >= 90) {
return "A";
} else if (avg >= 75) {
return "B";
} else if (avg >= 50) {
return "C";
} else {
return "F";
}
}
public String getName() {
return name;
}
}
public class StudentManager {
public static void main(String[] args) {
Student s1 = new Student("Aung Aung", 101);
s1.addScore("Math", 95);
s1.addScore("English", 82);
s1.addScore("Science", 88);
System.out.println(s1.getName() + " - Average: " + s1.calculateAverage()
+ " - Grade: " + s1.getGrade());
}
}The console will print the result in a format like Aung Aung - Average: 88.33... - Grade: B.5-Minute Try-It
Try changing the grade boundaries (e.g. >=80 for A), give two students different scores, and see how the grades differ — all within 5 minutes.
A Quick Word of Caution
HashMap's values() order isn't guaranteed to match insertion order. It doesn't matter for the average calculation, but do double-check your iteration logic.