本文將引導你完成一個經典的 Java 入門練習:設計一個 Student 類封裝學生資料與行為,並編寫 StudentDemo 測試類實現交互式輸入、成績計算與三好學生評定。
所有屬性聲明為 private,提供公共的 getter/setter 方法,確保資料封裝性:
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 getChinese() { return chinese; }
public void setChinese(float chinese) { this.chinese = chinese; }
public float getMath() { return math; }
public void setMath(float math) { this.math = math; }
public float getEnglish() { return english; }
public void setEnglish(float english) { this.english = english; }
// 業務方法
public void score() {
float sum = chinese + math + english;
System.out.println("總成績為:" + sum);
}
public void average() {
float avg = (chinese + math + english) / 3;
System.out.println("平均成績為:" + avg);
}
public void goodStudent() {
float avg = (chinese + math + english) / 3;
if (avg >= 90) {
System.out.println("是三好學生");
} else {
System.out.println("不是三好學生");
}
}
}
使用 JOptionPane 實現圖形化輸入對話框,驗證分數範圍 (1-100),並調用 Student 方法輸出結果:
import javax.swing.JOptionPane;
public class StudentDemo {
public static void main(String[] args) {
// 1. 創建學生對象(使用自己的姓名、學號)
Student stu = new Student("李四", "2023001");
// 2. 通過輸入對話框獲取成績,驗證範圍
stu.setChinese(getValidScore("語文"));
stu.setMath(getValidScore("數學"));
stu.setEnglish(getValidScore("英語"));
// 3. 輸出基本信息
System.out.println("姓名:" + stu.getName());
System.out.println("學號:" + stu.getId());
System.out.println("語文:" + stu.getChinese() + " 數學:" + stu.getMath() + " 英語:" + stu.getEnglish());
// 4. 調用業務方法
stu.score();
stu.average();
stu.goodStudent();
}
// 輔助方法:循環輸入直到獲得有效分數 (1-100)
private static float getValidScore(String subject) {
float score = -1;
while (score < 1 || score > 100) {
String input = JOptionPane.showInputDialog("請輸入" + subject + "成績 (1-100):");
try {
score = Float.parseFloat(input);
if (score < 1 || score > 100) {
JOptionPane.showMessageDialog(null, "分數必須在 1-100 之間!");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "請輸入有效數字!");
}
}
return score;
}
}
JOptionPane 簡單實現桌面應用輸入輸出。這個練習涵蓋了 Java 面向對象基礎、異常處理、標準庫使用等核心技能,是入門階段的優質綜合實戰。