Mini Project Set 4 Answer: Student Score Report
Complete Program
import java.util.ArrayList;
import java.util.HashMap;
class Student {
private String name;
private int score;
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String getGrade() {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else {
return "F";
}
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("Mina", 88));
students.add(new Student("Jin", 72));
students.add(new Student("Hana", 95));
students.add(new Student("Leo", 95));
students.add(new Student("Sara", 54));
HashMap<String, Integer> gradeCounts = new HashMap<>();
int totalScores = 0;
int bestIndex = 0;
int passingStudents = 0;
for (int i = 0; i < students.size(); i++) {
Student s = students.get(i);
String grade = s.getGrade();
System.out.println(s.getName() + ": " + s.getScore() + " (" + grade + ")");
totalScores += s.getScore();
if (s.getScore() > students.get(bestIndex).getScore()) {
bestIndex = i;
}
if (s.getScore() >= 60) {
passingStudents++;
}
if (gradeCounts.containsKey(grade)) {
gradeCounts.put(grade, gradeCounts.get(grade) + 1);
} else {
gradeCounts.put(grade, 1);
}
}
double average = (double) totalScores / students.size();
System.out.printf("Average score: %.2f%n", average);
System.out.println("Top student: " + students.get(bestIndex).getName());
System.out.println("Passing students: " + passingStudents);
String[] grades = {"A", "B", "C", "D", "F"};
for (String grade : grades) {
if (gradeCounts.containsKey(grade)) {
System.out.println(grade + " grades: " + gradeCounts.get(grade));
}
}
}
}
Output
Mina: 88 (B)
Jin: 72 (C)
Hana: 95 (A)
Leo: 95 (A)
Sara: 54 (F)
Average score: 80.80
Top student: Hana
Passing students: 4
A grades: 2
B grades: 1
C grades: 1
F grades: 1
Key Points
- The
Student class encapsulates its own data, and getGrade() owns the grading rules.
ArrayList<Student> stores objects in order, and an index is used to remember the top student.
gradeCounts uses each letter grade as a key and the number of students as the value.
containsKey + get + put increases an existing count without losing it.
- A
double cast is needed before calculating the average.