學生成績錄入系統,需要判斷成績格式合格,使用throw彈出,最後並列印全班成績單

碼個️發表於2020-11-28

實現思路:
1.寫出學生類,生成無參和滿參的建構函式,然後再生成get,set方法和懶狗的tosrting方法.
2.寫異常類,實現父類RuntimeException,並寫msg函式
3.測試類,用ArrayList建立一個學生類的集合,然後在測試類寫一個錄入成績的方法,然後在錄入成績方法裡面判斷,如果成績格式不合格,用throw彈出,否則生成一個新學生,然後返回給主函式,儲存在list中。
程式碼實現:
學生類:

package Test;

public class Student {
    private String name;
    private int gread;

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGread() {
        return gread;
    }

    public void setGread(int gread) {
        this.gread = gread;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", gread=" + gread +
                '}';
    }
}

異常類:

package Test;

public class Gread extends RuntimeException {
    private String msg;

    public Gread(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

}

測試類:

package Test;


import java.util.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        try {
            list.add(setGread(100, "王某"));
            list.add(setGread(99, "高某"));
            list.add(setGread(98, "周某"));
            list.add(setGread(97, "劉某"));
            list.add(setGread(197, "陳某"));
        } catch (Gread e) {
            System.out.println(e.getMsg());
        }
        System.out.println(list);
    }

    public static Student setGread(int a, String name) {
        Student student = new Student();
        if (a < 0 || a > 100) {
            throw new Gread(name + "成績格式違規");
        }
        student.setGread(a);
        student.setName(name);
        System.out.println(name + "錄入成功");
        return student;
    }
}

列印結果:
idea
喜歡的點贊,不喜歡的解散。

相關文章