java创建类Computer,该类中有一个计算两个数的最大公约数的方法,如果向该方法传递负整数,该方法就会抛出自定义异常
时间: 2023-10-09 13:05:17 浏览: 103
好的,我理解了你的问题。下面是 Computer 类的代码实现,包括计算最大公约数的方法和自定义异常的处理:
```java
public class Computer {
public int gcd(int a, int b) throws NegativeNumberException {
if (a < 0 || b < 0) {
throw new NegativeNumberException("传递的数为负整数");
}
int temp;
while (b > 0) {
temp = a % b;
a = b;
b = temp;
}
return a;
}
}
public class NegativeNumberException extends Exception {
public NegativeNumberException() {
super();
}
public NegativeNumberException(String message) {
super(message);
}
}
```
在上面的代码中,我们定义了一个计算最大公约数的方法 gcd(int a, int b),如果传递的参数 a 或 b 是负整数,则会抛出自定义异常 NegativeNumberException。
当然,你也可以使用 RuntimeException 的子类 IllegalArgumentException 来处理非法参数的情况,这样就不需要在方法签名中声明 throws 了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)