Student类有一个输入分数的setSocre(int score)方法,对象调用该方法是必须向参数传递一个0-150之间的正整数,否则方法就抛出异常。自定义一个异常类完成此分数的检查,并编写测试类,对上述方法进行测试。
时间: 2023-12-03 21:47:00 浏览: 25
下面是自定义的异常类`ScoreException`的代码实现:
```java
public class ScoreException extends Exception {
public ScoreException(String message) {
super(message);
}
}
```
`Student`类的`setScore`方法实现如下:
```java
public void setScore(int score) throws ScoreException {
if (score < 0 || score > 150) {
throw new ScoreException("分数必须在0-150之间!");
}
this.score = score;
}
```
下面是测试类的代码实现:
```java
public class Test {
public static void main(String[] args) {
Student s = new Student();
try {
s.setScore(80); // 设置合法分数
System.out.println("分数设置成功!");
} catch (ScoreException e) {
System.out.println(e.getMessage());
}
try {
s.setScore(-10); // 设置非法分数
System.out.println("分数设置成功!");
} catch (ScoreException e) {
System.out.println(e.getMessage());
}
}
}
```
输出结果:
```
分数设置成功!
分数必须在0-150之间!
```