阿摩線上測驗 登入

申論題資訊

試卷:99年 - 099年專門職業及技術人員高等建築師、技師暨普通不動產經紀人、記帳士資訊技師#32440
科目:程式設計
年份:99年
排序:0

題組內容

一個班級 40 位同學,考完期中考,已經知道國文、數學成績,請撰寫適當程式碼解決 下列問題(若題目規範有不周之處,請自行假設並說明之);程式必須採取物件導向方 式設計,儘量採用類別、繼承、封裝、多型等技巧,可採用上述技巧而未採用者將會影 響其得分:

申論題內容

三、計算同學個別的總分及平均、各科全體的總分及平均。(10 分)

詳解 (共 1 筆)

詳解 提供者:hchungw
擴展 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類的適當擴展,我們能夠滿足題目的需求,同時也保留了對未來需求變化的適應性。