Java Mini Project: Student Grade Tracker
In this project you'll build a small but complete program step by step: a grade tracker that stores students and their exam scores, calculates averages and letter grades, prints a ranked report, and saves the data to a CSV file. Along the way you'll use records, classes, collections, switch expressions, streams, exceptions and file I/O — most of what this course has covered.
Each step is a complete program that you can run and modify. Every step builds on the previous one.
| Step | Feature | Concepts used |
|---|---|---|
| 1 | Model a student | records, lists, compact constructor |
| 2 | A grade book | classes, encapsulation, maps, exceptions |
| 3 | Letter grades | switch expressions, enums |
| 4 | Ranked report | streams, comparators, printf |
| 5 | Statistics | grouping collectors, Optional |
| 6 | Save and load | files, text blocks, parsing |
Step 1: Model a student
A student has a name and a list of scores. A record is perfect for this. The compact constructor validates the scores and stores an unmodifiable copy so the record stays immutable:
import java.util.List;
record Student(String name, List<Integer> scores) {
Student {
if (name == null || name.isBlank()) throw new IllegalArgumentException("Name required");
for (int s : scores) {
if (s < 0 || s > 100) throw new IllegalArgumentException("Invalid score " + s + " for " + name);
}
scores = List.copyOf(scores);
}
double average() {
if (scores.isEmpty()) return 0;
int sum = 0;
for (int s : scores) sum += s;
return (double) sum / scores.size();
}
}
class Main {
public static void main(String[] args) {
Student ada = new Student("Ada", List.of(92, 88, 95));
System.out.println(ada);
System.out.printf("%s averages %.1f%n", ada.name(), ada.average());
try {
new Student("Bob", List.of(70, 120));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Student[name=Ada, scores=[92, 88, 95]]
Ada averages 91.7
Rejected: Invalid score 120 for Bob
Step 2: A grade book
Next, a GradeBook class manages many students. A LinkedHashMap keyed by name keeps them in the order they were added and makes lookups fast. Because records are immutable, adding a score replaces the student with an updated copy:
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
record Student(String name, List<Integer> scores) {
Student {
scores = List.copyOf(scores);
}
double average() {
return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
}
}
class GradeBook {
private final Map<String, Student> students = new LinkedHashMap<>();
void addStudent(String name) {
if (students.containsKey(name)) {
throw new IllegalArgumentException(name + " already exists");
}
students.put(name, new Student(name, List.of()));
}
void addScore(String name, int score) {
Student s = students.get(name);
if (s == null) throw new IllegalArgumentException("Unknown student: " + name);
if (score < 0 || score > 100) throw new IllegalArgumentException("Invalid score: " + score);
List<Integer> updated = new ArrayList<>(s.scores());
updated.add(score);
students.put(name, new Student(name, updated));
}
Collection<Student> all() {
return students.values();
}
}
class Main {
public static void main(String[] args) {
GradeBook book = new GradeBook();
book.addStudent("Ada");
book.addStudent("Ben");
book.addScore("Ada", 92);
book.addScore("Ada", 88);
book.addScore("Ben", 61);
book.addScore("Ben", 74);
try {
book.addScore("Zoe", 80);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
for (Student s : book.all()) {
System.out.printf("%-4s %s avg %.1f%n", s.name(), s.scores(), s.average());
}
}
}Error: Unknown student: Zoe
Ada [92, 88] avg 90.0
Ben [61, 74] avg 67.5
Notice how GradeBook hides its map completely: other code can only add students and scores through methods that check the input.
Step 3: Letter grades
Turning an average into a letter grade is a job for an enum: each constant stores its minimum average, a static method finds the matching grade, and a switch expression adds a friendly comment:
enum Grade {
A(90), B(80), C(70), D(60), F(0);
private final int minimum;
Grade(int minimum) {
this.minimum = minimum;
}
static Grade of(double average) {
for (Grade g : values()) { // values() are in declaration order: A first
if (average >= g.minimum) return g;
}
return F;
}
String comment() {
return switch (this) {
case A -> "excellent";
case B -> "good";
case C -> "satisfactory";
case D -> "needs improvement";
case F -> "failed";
};
}
}
class Main {
public static void main(String[] args) {
double[] averages = {95.5, 83.0, 70.0, 64.9, 41.2};
for (double avg : averages) {
Grade g = Grade.of(avg);
System.out.printf("%5.1f -> %s (%s)%n", avg, g, g.comment());
}
}
} 95.5 -> A (excellent)
83.0 -> B (good)
70.0 -> C (satisfactory)
64.9 -> D (needs improvement)
41.2 -> F (failed)
Keeping the thresholds inside the enum means changing the grading scheme touches exactly one place.
Step 4: A ranked report
Now combine the pieces. A stream sorts students by average (best first, then by name for ties) and prints a neatly aligned table with a rank column:
import java.util.Comparator;
import java.util.List;
record Student(String name, List<Integer> scores) {
double average() {
return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
}
}
enum Grade {
A(90), B(80), C(70), D(60), F(0);
private final int min;
Grade(int min) { this.min = min; }
static Grade of(double avg) {
for (Grade g : values()) if (avg >= g.min) return g;
return F;
}
}
class Main {
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Ben", List.of(61, 74, 70)),
new Student("Ada", List.of(92, 88, 95)),
new Student("Chloe", List.of(85, 79, 91)),
new Student("Dev", List.of(55, 48, 62)),
new Student("Eli", List.of(91, 89, 92)));
List<Student> ranked = students.stream()
.sorted(Comparator.comparingDouble(Student::average).reversed()
.thenComparing(Student::name))
.toList();
System.out.println("Rank Name Avg Grade");
System.out.println("---- ------ ----- -----");
for (int i = 0; i < ranked.size(); i++) {
Student s = ranked.get(i);
System.out.printf("%4d %-6s %5.1f %s%n", i + 1, s.name(), s.average(), Grade.of(s.average()));
}
}
}Rank Name Avg Grade
---- ------ ----- -----
1 Ada 91.7 A
2 Eli 90.7 A
3 Chloe 85.0 B
4 Ben 68.3 D
5 Dev 55.0 F
Step 5: Class statistics
Teachers want an overview: the class average, the best student, and how many students received each grade. Collectors.groupingBy with an EnumMap keeps the grades in A–F order:
import java.util.Comparator;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
record Student(String name, List<Integer> scores) {
double average() {
return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
}
}
enum Grade {
A(90), B(80), C(70), D(60), F(0);
private final int min;
Grade(int min) { this.min = min; }
static Grade of(double avg) {
for (Grade g : values()) if (avg >= g.min) return g;
return F;
}
}
class Main {
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Ben", List.of(61, 74, 70)),
new Student("Ada", List.of(92, 88, 95)),
new Student("Chloe", List.of(85, 79, 91)),
new Student("Dev", List.of(55, 48, 62)),
new Student("Eli", List.of(91, 89, 92)));
double classAvg = students.stream().mapToDouble(Student::average).average().orElse(0);
System.out.printf("Class average: %.1f%n", classAvg);
Optional<Student> best = students.stream().max(Comparator.comparingDouble(Student::average));
best.ifPresent(s -> System.out.println("Top student: " + s.name()));
Map<Grade, Long> distribution = students.stream()
.collect(Collectors.groupingBy(s -> Grade.of(s.average()),
() -> new EnumMap<>(Grade.class), Collectors.counting()));
for (Grade g : Grade.values()) {
long n = distribution.getOrDefault(g, 0L);
System.out.printf("%s: %s%n", g, "#".repeat((int) n));
}
List<String> atRisk = students.stream()
.filter(s -> s.average() < 60)
.map(Student::name)
.toList();
System.out.println("At risk: " + atRisk);
}
}Class average: 78.1
Top student: Ada
A: ##
B: #
C:
D: #
F: #
At risk: [Dev]
Step 6: Save and load
Finally, the data should survive between runs. We save each student as one CSV line — name;score,score,... — and parse it back. A temporary file keeps the playground clean; in a real app you'd use a fixed path like Path.of("grades.csv"):
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
record Student(String name, List<Integer> scores) {
double average() {
return scores.stream().mapToInt(Integer::intValue).average().orElse(0);
}
String toCsv() {
String joined = scores.stream().map(String::valueOf).collect(Collectors.joining(","));
return name + ";" + joined;
}
static Student fromCsv(String line) {
String[] parts = line.split(";", 2);
if (parts.length != 2) throw new IllegalArgumentException("Bad line: " + line);
List<Integer> scores = parts[1].isBlank()
? List.of()
: Arrays.stream(parts[1].split(",")).map(String::trim).map(Integer::parseInt).toList();
return new Student(parts[0], scores);
}
}
class Main {
public static void main(String[] args) throws IOException {
List<Student> students = List.of(
new Student("Ada", List.of(92, 88, 95)),
new Student("Ben", List.of(61, 74, 70)),
new Student("Nia", List.of()));
Path file = Files.createTempFile("grades", ".csv");
Files.write(file, students.stream().map(Student::toCsv).toList());
System.out.print("Saved file:\n" + Files.readString(file));
// Simulate a damaged line added by hand
Files.writeString(file, Files.readString(file) + "oops-no-separator\n");
List<Student> loaded = new ArrayList<>();
int lineNo = 0;
for (String line : Files.readAllLines(file)) {
lineNo++;
try {
loaded.add(Student.fromCsv(line));
} catch (IllegalArgumentException e) {
System.out.println("Skipping line " + lineNo + ": " + e.getMessage());
}
}
Files.delete(file);
System.out.println("Loaded " + loaded.size() + " students:");
for (Student s : loaded) {
System.out.printf(" %-4s %-14s avg %.1f%n", s.name(), s.scores(), s.average());
}
}
}Saved file:
Ada;92,88,95
Ben;61,74,70
Nia;
Skipping line 4: Bad line: oops-no-separator
Loaded 3 students:
Ada [92, 88, 95] avg 91.7
Ben [61, 74, 70] avg 68.3
Nia [] avg 0.0
The loader is defensive: a broken line is reported and skipped instead of crashing the whole program, and a student without scores (Nia;) is handled explicitly.
Ideas for extending the project
- Add weighted scores (e.g. the final exam counts double) by storing
record Score(String exam, int points, double weight). - Read commands from a
Scanner(add Ada,score Ada 90,report,save) to make it interactive on your own machine. - Export the report as a text block formatted like a Markdown table.
- Write unit tests for
Grade.ofandStudent.fromCsvwith JUnit.
Tip: Notice how each step added one responsibility in one place:
Studentknows its data,Gradeknows the grading scheme, and the reporting code only combines them. Keeping responsibilities separate is what lets small programs grow without becoming a mess.
Test yourself
Why does the Student record call List.copyOf(scores) in its compact constructor?
- To sort the scores
- To store an unmodifiable copy so outside code can't change the record's data
- To remove duplicates
- Records require it
Why is an EnumMap used for the grade distribution?
- It is the only map that accepts enums
- It keeps keys in the enum's declaration order (A to F)
- It counts automatically
- It allows duplicate keys
What does the loader do with a line that has no ; separator?
- Crashes the program
- Treats it as a student without scores
- Reports and skips it
- Saves it again