Explain it simply
Explain it simply
In Part 1 the registration cards went neatly into the cabinet. Now each card gets its subjects and marks written on the back, like "Math 95, English 82". When a teacher re-marks Math, the old mark is crossed out and the new one written in; a subject never appears twice.
The card should also answer "what is my average, and what grade is that?" by itself, so the average and grade methods go inside the Student class. A card with no marks at all has not failed. It simply has not been graded yet.
Problem → Why → Solution
The problem: an average of 88.33 comes out as 88
The first draft divides an int total by size() and stores the result in a double. Aung Aung's 95 + 82 + 88 = 265 divided by 3 should be 88.33, but the program prints 88.0. For a student near a threshold, that missing 0.33 can even change the grade.
The second bug hits Mya Mya, who has no scores yet. With an empty map, size() is 0, so 0 / 0 throws an ArithmeticException and the program stops. "Just return 0" fixes the crash but gives Mya Mya an F, and her parents receive a report saying she failed.
public double calculateAverage() {
int total = 0;
for (int score : subjectScores.values()) {
total += score;
}
return total / subjectScores.size(); // int / int: 265 / 3 == 88
} // empty map: 0 / 0 throwsWhy doesn't the double return type save it?
Java evaluates an expression using its operands' types and only afterwards widens the result to the return type. total and size() are both int, so the division is integer division and the fraction is thrown away; only then is 88 widened to 88.0. Integer division by 0 throws an ArithmeticException.
Core concept: store scores, derive average and grade on demand
The key design decision in Part 2 is what to store and what to compute. Scores are source data, so they live in the map. The average and the grade are derived from the scores, so they are not stored as fields; they are recalculated every time the method is called. That way there is never a stale average left behind after a score changes.
1. put() both adds and updates
A map holds one value per key. Calling addScore("Math", 61) on a student who already has Math replaces 45 with 61, and the subject count stays the same. For re-marking, that is exactly the behaviour you want.
2. Sum values(), cast, then divide
values() returns the scores as an Integer collection, and for (int score : ...) unboxes each one. Casting the total to double before dividing by size() makes it a floating-point division.
3. Handle the empty case first
With no scores, calculateAverage() returns 0.0 and getGrade() returns "-". The average can only return a number, so it uses 0.0, but the grade uses a separate marker so it can never be confused with "F".
4. Check thresholds from the top
>= 90 gives A, >= 75 gives B, >= 50 gives C, anything else F. For 88.33 the first true test is >= 75, so the grade is B.
What an unmodifiable view is
Collections.unmodifiableMap(subjectScores) is not a copy; it is a read-only window onto the real map. A caller who calls put() on it gets an UnsupportedOperationException. Every change must go through addScore(), so when Part 3 adds validation there is only one place to put it.
- addScore() puts into the map
- calculateAverage() recomputes each call
- getGrade() maps the average to a letter
- The grade sheet only calls methods
The less you store, the less there is to fall out of sync.
General pattern
double average() {
if (values.isEmpty()) return 0.0;
int total = 0;
for (int v : values.values()) total += v;
return (double) total / values.size();
}
String label() {
if (values.isEmpty()) return "-";
double avg = average();
return avg >= TOP ? "A" : avg >= MID ? "B" : "C";
}Handle the empty case first, cast before dividing, then test thresholds from the top. Derived values come from methods, not stored fields.
Part 2 code: the grade sheet
This example keeps Part 1's Student, StudentManager and StudentApp and adds only the sections marked "NEW in Part 2". Watch the import lines at the top: ArrayList, LinkedHashMap, List and Map live in java.util, and without those imports the compiler cannot find them and the file does not compile. StudentApp, which holds main, is the first class after the imports so that java StudentApp.java can run it. In the output, look at Ko Ko's Math being re-marked from 45 to 61 and at Mya Mya's grade "-".
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class StudentApp {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Student aung = new Student("Aung Aung", 101);
Student suSu = new Student("Su Su", 102);
Student koKo = new Student("Ko Ko", 103);
manager.addStudent(aung);
manager.addStudent(suSu);
manager.addStudent(koKo);
manager.addStudent(new Student("Mya Mya", 104)); // no scores yet
aung.addScore("Math", 95);
aung.addScore("English", 82);
aung.addScore("Science", 88);
suSu.addScore("Math", 72);
suSu.addScore("English", 91);
suSu.addScore("Science", 67);
koKo.addScore("Math", 45);
koKo.addScore("English", 58);
koKo.addScore("Math", 61); // re-marked: put() replaces the old 45
manager.printGradeSheet();
System.out.println("Ko Ko's scores: " + koKo.getScores());
}
}
class Student {
private final String name;
private final int id;
private final Map<String, Integer> subjectScores;
public Student(String name, int id) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("name must not be blank");
}
if (id <= 0) {
throw new IllegalArgumentException("id must be positive, got " + id);
}
this.name = name.strip();
this.id = id;
this.subjectScores = new LinkedHashMap<>();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
// NEW in Part 2 ------------------------------------------------
public void addScore(String subject, int score) {
subjectScores.put(subject, score); // same subject again = update
}
public Map<String, Integer> getScores() {
return Collections.unmodifiableMap(subjectScores);
}
public double calculateAverage() {
if (subjectScores.isEmpty()) {
return 0.0;
}
int total = 0;
for (int score : subjectScores.values()) {
total += score;
}
return (double) total / subjectScores.size();
}
public String getGrade() {
if (subjectScores.isEmpty()) {
return "-"; // not graded yet, which is not the same as failing
}
double avg = calculateAverage();
if (avg >= 90) {
return "A";
} else if (avg >= 75) {
return "B";
} else if (avg >= 50) {
return "C";
} else {
return "F";
}
}
}
class StudentManager {
private final List<Student> students = new ArrayList<>();
public boolean addStudent(Student student) {
if (findById(student.getId()) != null) {
return false;
}
students.add(student);
return true;
}
public Student findById(int id) {
for (Student s : students) {
if (s.getId() == id) {
return s;
}
}
return null;
}
// printRoster() from Part 1 is unchanged and left out to keep this short.
// NEW in Part 2 ------------------------------------------------
public void printGradeSheet() {
for (Student s : students) {
System.out.printf("%d %-9s subjects=%d avg=%.2f grade=%s%n",
s.getId(), s.getName(), s.getScores().size(),
s.calculateAverage(), s.getGrade());
}
}
}Code breakdown
- Add or update in one call
subjectScores.put(subject, score); // same subject again = updateKo Ko's Math is put twice, so he still has subjects=2 and Math=61. (61 + 58) / 2 = 59.5, which is a C.
- Read-only view for callers
return Collections.unmodifiableMap(subjectScores);printGradeSheet() and main can read the scores but not change them. Because the map is a LinkedHashMap, printing it shows {Math=61, English=58} in insertion order.
- Floating-point division
return (double) total / subjectScores.size();The cast happens before the division, so 265.0 / 3 = 88.333..., which %.2f prints as 88.33.
- Not graded is not failed
return "-"; // not graded yet, which is not the same as failingMya Mya's average shows 0.00, but her grade is "-", not F, so a reader can tell "not graded yet" from "failed".
- Formatted columns
System.out.printf("%d %-9s subjects=%d avg=%.2f grade=%s%n",%-9s left-aligns the name in a 9-character column so the rows line up, and %n is the platform's newline.
101 Aung Aung subjects=3 avg=88.33 grade=B
102 Su Su subjects=3 avg=76.67 grade=B
103 Ko Ko subjects=2 avg=59.50 grade=C
104 Mya Mya subjects=0 avg=0.00 grade=-
Ko Ko's scores: {Math=61, English=58}Test the grade rule at its boundaries
The best values for testing a grade rule sit just above and just below each threshold. 90 must be an A and 89.99 must be a B; check 75 against 74.99 and 50 against 49.99 the same way. If someone accidentally writes > instead of >=, a student with exactly 90 would get a B, and these tests catch that immediately.
Comparing doubles has one more catch. Averages are divisions by the number of scores, so values like 89.99999 can appear. If the school's policy is "round to one decimal place, then grade", write that rounding explicitly inside getGrade() so the rule is visible.
In real projects
In real projects
A shop's cart total, a bank account's balance and a student portal's GPA are all derived data. Most teams recompute them from the source data (line items, transactions, scores) and only cache when performance truly demands it. Even then, the cache is updated from a single place whenever the source changes; in this project that place would be addScore().
Grading scales differ between schools and years. The Mini Project used 80 for an A and this project uses 90, which proves the point. Real systems usually read thresholds from configuration or a database table instead of hard-coding them. Storing marks as int rather than double, and formatting the average only when printing a report, are also good habits that keep rounding problems small.
Common mistakes
Common mistakes
Dividing int by int without a (double) cast
return total / subjectScores.size(); compiles and returns 88.0. The double return type makes it look right, but the fraction was already lost during the division. Cast one operand to double.
Checking >= 50 before >= 90
With if (avg >= 50) first, a student averaging 95 gets a C, because the chain stops at the first true branch. Start from the highest threshold and test the boundary values.
Grading an empty student as F
If an empty map averages to 0.0 and getGrade() then grades that 0.0, a student who has not sat any exam gets an F. Check isEmpty() inside getGrade() as well.
Returning the live map from a getter
If getScores() returns subjectScores itself, a caller can write getScores().put("Math", 500) and bypass addScore(), along with the 0-100 check that Part 3 adds there.
Mini challenge
Best subject, top student and class average
Add getBestSubject() to Student, and findTopStudent() and classAverage() to StudentManager. Students without scores must be ignored both when choosing the top student and when computing the class average.
- getBestSubject() returns the subject with the highest score, or "none" with no scores
- On a tie, keep the subject that was added first
- findTopStudent() returns null when no student has been graded
- classAverage() averages only the averages of graded students
import java.util.*;
public class GradeChallenge {
public static void main(String[] args) {
// TODO: three students, one with no scores; print best subjects,
// the top student and the class average (two decimals)
}
}
class Student {
// name, id, subjectScores, addScore(), calculateAverage() from the lesson
boolean hasScores() { /* TODO */ return false; }
String getBestSubject() {
// TODO: walk entrySet(), keep the first highest score
return "none";
}
}
class StudentManager {
private final List<Student> students = new ArrayList<>();
Student findTopStudent() { /* TODO: skip students without scores */ return null; }
double classAverage() { /* TODO: guard against zero graded students */ return 0; }
}Expected: With Aung Aung (Math 95, English 82) and Su Su (Math 72, English 91, Science 91), the best subjects are Math and English, the top student is Aung Aung, and the class average is 86.58.
Show hint
Loop over entrySet() and compare with a strict e.getValue() > bestScore, so the first subject survives a tie. In classAverage(), check graded == 0 before dividing.
Show solution
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class GradeChallenge {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
Student aung = manager.add(new Student("Aung Aung", 101));
Student suSu = manager.add(new Student("Su Su", 102));
manager.add(new Student("Mya Mya", 104)); // no scores
aung.addScore("Math", 95);
aung.addScore("English", 82);
suSu.addScore("Math", 72);
suSu.addScore("English", 91);
suSu.addScore("Science", 91);
System.out.println("Aung Aung best subject: " + aung.getBestSubject());
System.out.println("Su Su best subject: " + suSu.getBestSubject());
Student top = manager.findTopStudent();
System.out.println("Top student: " + (top == null ? "none" : top.getName()));
System.out.printf("Class average (graded only): %.2f%n", manager.classAverage());
}
}
class Student {
private final String name;
private final int id;
private final Map<String, Integer> subjectScores = new LinkedHashMap<>();
Student(String name, int id) {
this.name = name;
this.id = id;
}
String getName() { return name; }
boolean hasScores() { return !subjectScores.isEmpty(); }
void addScore(String subject, int score) {
subjectScores.put(subject, score);
}
double calculateAverage() {
if (subjectScores.isEmpty()) return 0.0;
int total = 0;
for (int score : subjectScores.values()) total += score;
return (double) total / subjectScores.size();
}
String getBestSubject() {
String best = "none";
int bestScore = -1;
for (Map.Entry<String, Integer> e : subjectScores.entrySet()) {
if (e.getValue() > bestScore) { // strict >, so the first of a tie wins
best = e.getKey();
bestScore = e.getValue();
}
}
return best;
}
}
class StudentManager {
private final List<Student> students = new ArrayList<>();
Student add(Student s) {
students.add(s);
return s;
}
Student findTopStudent() {
Student top = null;
for (Student s : students) {
if (!s.hasScores()) {
continue;
}
if (top == null || s.calculateAverage() > top.calculateAverage()) {
top = s;
}
}
return top;
}
double classAverage() {
double sum = 0;
int graded = 0;
for (Student s : students) {
if (s.hasScores()) {
sum += s.calculateAverage();
graded++;
}
}
return graded == 0 ? 0.0 : sum / graded;
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- put() in addScore() both adds a new subject and re-marks an existing one
- Compute average and grade from the scores on each call instead of storing them
- Cast to double before dividing, and handle the empty map first
- Keep "not graded" apart from "failed": "-" is not "F"
- Expose the map as an unmodifiable view so addScore() is the only way to change scores