阿摩線上測驗 登入

申論題資訊

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

題組內容

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

申論題內容

二、按學號讀入全體同學的成績。(10 分)

詳解 (共 1 筆)

詳解 提供者:hchungw

 

封裝(Encapsulation: 使用類來封裝學生的資訊和成績。

繼承(Inheritance: 雖然這個具體的場景可能不需要複雜的繼承結構,但我們會展示如何為未來可能的需求預留空間。

多態(Polymorphism: 我們將通過介面或抽象類展示多態的使用,以便未來可以容易地擴展功能。

設計思路

Student 類:代表單個學生,包含學生的基本資訊(如學號、姓名)和成績(國文和數學)。

Classroom 類:管理整個班級的學生資訊,包括添加學生和按學號讀入成績。

實現代碼

Student

java

Copy code

public class Student {

    private String id; // 學號

    private String name; // 姓名

    private int chineseScore; // 國文成績

    private int mathScore; // 數學成績

 

    // 構造函數

    public Student(String id, String name) {

        this.id = id;

        this.name = name;

    }

 

    // 封裝:屬性的 getters setters

    public String getId() {

        return id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public int getChineseScore() {

        return chineseScore;

    }

 

    public void setChineseScore(int chineseScore) {

        this.chineseScore = chineseScore;

    }

 

    public int getMathScore() {

        return mathScore;

    }

 

    public void setMathScore(int mathScore) {

        this.mathScore = mathScore;

    }

}

Classroom

java

Copy code

import java.util.HashMap;

import java.util.Map;

 

public class Classroom {

    private Map<String, Student> students; // 使用學號作為鍵來存儲學生對象

 

    public Classroom() {

        students = new HashMap<>();

    }

 

    // 添加學生

    public void addStudent(Student student) {

        students.put(student.getId(), student);

    }

 

    // 按學號更新學生的成績

    public void updateScores(String id, int chineseScore, int mathScore) {

        Student student = students.get(id);

        if (student != null) {

            student.setChineseScore(chineseScore);

            student.setMathScore(mathScore);

        } else {

            System.out.println("Student with ID " + id + " not found.");

        }

    }

 

    // 其他班級管理方法...

}

解決方案說明

Student 類封裝了單個學生的資訊和成績。

Classroom 類管理一個班級的學生,提供了添加學生和按學號更新成績的功能。

封裝:通過私有屬性和公開方法對學生資訊進行封裝,確保數據的安全性。

繼承和多態:雖然在這個簡單場景中我們沒有直接用到繼承和多態,但系統設計保留了這種可能性。例如,如果將來有不同類型的學生(如國際生或特殊需求學生),可以通過繼承Student類並覆寫相關方法來實現多態和特殊處理。

這個設計方案提供了一種結構化和靈活的方式來管理班級學生的成績,並且遵循了面向對象設計的主要原則。