擴展 Student 類
我們給Student類添加一個方法來計算個別學生的總分和平均分。
java
Copy code
public class Student {
// 省略之前的屬性和方法定義...
// 計算個別學生的總分
public int getTotalScore() {
return chineseScore + mathScore;
}
// 計算個別學生的平均分
public double getAverageScore() {
return getTotalScore() / 2.0;
}
}
擴展 Classroom 類
我們將Classroom類擴展以計算全班的總分和平均分。
java
Copy code
import java.util.Map;
import java.util.HashMap;
public class Classroom {
private Map<String, Student> students;
public Classroom() {
students = new HashMap<>();
}
// 省略之前的方法...
// 計算全班各科的總分
public int[] getClassTotalScores() {
int totalChineseScore = 0;
int totalMathScore = 0;
for (Student student : students.values()) {
totalChineseScore += student.getChineseScore();
totalMathScore += student.getMathScore();
}
return new int[]{totalChineseScore, totalMathScore};
}
// 計算全班各科的平均分
public double[] getClassAverageScores() {
int[] totalScores = getClassTotalScores();
double averageChineseScore = (double)totalScores[0] / students.size();
double averageMathScore = (double)totalScores[1] / students.size();
return new double[]{averageChineseScore, averageMathScore};
}
}
使用
假設我們已經有了一個Classroom實例classroom和一組Student實例,我們可以這樣計算並列印平均分和總分:
java
Copy code
public static void main(String[] args) {
Classroom classroom = new Classroom();
// 假設添加了學生到 classroom
// classroom.addStudent(new Student("ID1", "Student1", 90, 85));
// 重複添加其他學生...
// 列印全班的各科總分和平均分
int[] totalScores = classroom.getClassTotalScores();
System.out.println("全班國文總分: " + totalScores[0] + ", 數學總分: " + totalScores[1]);
double[] averageScores = classroom.getClassAverageScores();
System.out.println("全班國文平均分: " + averageScores[0] + ", 數學平均分: " + averageScores[1]);
// 列印個別學生的總分和平均分
for (Student student : classroom.getStudents()) {
System.out.println(student.getName() + "的總分: " + student.getTotalScore() + ", 平均分: " + student.getAverageScore());
}
}
這個設計方案利用了面向對象編程的幾個核心原則,如封裝和擴展性,同時也提供了計算和管理學生成績的靈活方式。通過對Student和Classroom類的適當擴展,我們能夠滿足題目的需求,同時也保留了對未來需求變化的適應性。