Java代码实现Student类有一个输入分数的setSocre(int score)方法,对象调用该方法是必须向参数传递一个0-150之间的正整数,否则方法就抛出异常。自定义一个异常类完成此分数的检查,并编写测试类,对上述方法进行测试。
时间: 2023-12-03 10:47:03 浏览: 92
下面是Java代码实现:
```java
public class ScoreOutOfRangeException extends Exception {
private static final long serialVersionUID = 1L;
public ScoreOutOfRangeException(String message) {
super(message);
}
}
public class Student {
private int score;
public void setScore(int score) throws ScoreOutOfRangeException {
if (score < 0 || score > 150) {
throw new ScoreOutOfRangeException("分数必须在0-150之间!");
}
this.score = score;
}
public int getScore() {
return score;
}
}
public class TestStudent {
public static void main(String[] args) {
Student student = new Student();
try {
student.setScore(80);
System.out.println("分数为:" + student.getScore());
student.setScore(-10); // 抛出异常
} catch (ScoreOutOfRangeException e) {
System.out.println(e.getMessage());
}
}
}
```
测试结果:
```
分数为:80
分数必须在0-150之间!
```
阅读全文