設計 Student 類:私有屬性(姓名、學號、語數英成績),構造器重載、Getter/Setter、總分、平均分、三好學生判斷。編寫 StudentDemo 交互式測試。
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;
}
}
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, "輸入無效,請重新輸入!");
}
}
}
彈出輸入對話框依次錄入,最後彈出結果對話框展示所有信息。