首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 面向對象基礎練習:Student 類設計與 StudentDemo 測試類完整實現

     編輯:程式設計疑難解答

需求分析

設計 Student 類:私有屬性(姓名、學號、語數英成績),構造器重載、Getter/Setter、總分、平均分、三好學生判斷。編寫 StudentDemo 交互式測試。

Student 類完整代碼

public class Student {
    private String name;
    private String id;
    private float chinese;
    private float math;
    private float english;

    public Student() {
        this.name = "張三";
        this.id = "111111";
    }

    public Student(String name, String id) {
        this.name = name;
        this.id = id;
    }

    // Getter/Setter 省略...

    public float getTotalScore() {
        return chinese + math + english;
    }

    public float getAverageScore() {
        return getTotalScore() / 3;
    }

    public boolean isGoodStudent() {
        return getAverageScore() >= 90;
    }
}

StudentDemo 測試類

import javax.swing.JOptionPane;

public class StudentDemo {
    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog("請輸入姓名:");
        String id = JOptionPane.showInputDialog("請輸入學號:");

        Student stu = new Student(name, id);

        // 輸入成績,簡易驗證 0-100
        stu.setChinese(inputScore("語文"));
        stu.setMath(inputScore("數學"));
        stu.setEnglish(inputScore("英語"));

        // 輸出
        String msg = String.format(
            "姓名: %s\n學號: %s\n語文: %.1f\n數學: %.1f\n英語: %.1f\n" +
            "總分: %.1f\n平均分: %.1f\n是否三好學生: %s",
            stu.getName(), stu.getId(),
            stu.getChinese(), stu.getMath(), stu.getEnglish(),
            stu.getTotalScore(), stu.getAverageScore(),
            stu.isGoodStudent() ? "是" : "否"
        );
        JOptionPane.showMessageDialog(null, msg);
    }

    static float inputScore(String subject) {
        while (true) {
            String s = JOptionPane.showInputDialog("請輸入" + subject + "成績 (0-100):");
            try {
                float score = Float.parseFloat(s);
                if (score >= 0 && score <= 100) return score;
            } catch (NumberFormatException ignored) {}
            JOptionPane.showMessageDialog(null, "輸入無效,請重新輸入!");
        }
    }
}

運行效果

彈出輸入對話框依次錄入,最後彈出結果對話框展示所有信息。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved