自定義異常類
問題:
請使用代碼實現
每一個學生(Student)都有學號,姓名和分數,分數永遠不能為負數
如果老師給學生賦值一個負數,拋出一個自定異常
public class NoScoreException extends RuntimeException {public NoScoreException() {}public NoScoreException(String message
) {super(message
);}
}
public class Student {
private String name
;private int grade
;public Student() {}public Student(String name
, int grade
) {this.name
= name
;this.grade
= grade
;if (grade
< 0) {throw new NoScoreException("分數不能為負數" + grade
);}this.score(grade
);}public String
getName() {return name
;}public void setName(String name
) {this.name
= name
;}public int getGrade() {return grade
;}public void setGrade(int grade
) {this.grade
= grade
;}public void score(int score
){if (score
< 0) {throw new NoScoreException("分數不能為負數" + score
);}this.score(score
);}@Overridepublic boolean equals(Object o
) {if (this == o
) return true;if (o
== null
|| getClass() != o
.getClass()) return false;Student student
= (Student
) o
;return grade
== student
.grade
&&Objects
.equals(name
, student
.name
);}@Overridepublic int hashCode() {return Objects
.hash(name
, grade
);}@Overridepublic String
toString() {return "Student{" +"name='" + name
+ '\'' +", grade=" + grade
+'}';}
}
public class Test {public static void main(String
[] args
) {Student student1
= new Student("張三",-8);
}
}
總結
以上是生活随笔為你收集整理的# 自定义异常类 问题: 请使用代码实现 每一个学生(Student)都有学号,姓名和分数,分数永远不能为负数 如果老师给学生赋值一个负数,抛出一个自定异常的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。