JAVA创建一个computer类,该类中有一个计算两个数的最大公约数的方法,如果向该方法传递负整数,该方法就会抛出自定义异常。
时间: 2023-07-14 22:13:32 浏览: 117
下面是一个示例代码,实现了一个名为Computer的类,其中包含一个名为calculateGCD的方法,用于计算两个数的最大公约数。如果向该方法传递负整数,该方法就会抛出名为NegativeNumberException的自定义异常。
```
public class Computer {
public static int calculateGCD(int num1, int num2) throws NegativeNumberException {
if (num1 < 0 || num2 < 0) {
throw new NegativeNumberException("Negative numbers are not allowed.");
}
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}
public static void main(String[] args) {
try {
int gcd = Computer.calculateGCD(10, -5);
System.out.println("The GCD is: " + gcd);
} catch (NegativeNumberException e) {
System.out.println(e.getMessage());
}
}
}
class NegativeNumberException extends Exception {
public NegativeNumberException(String errorMessage) {
super(errorMessage);
}
}
```
在上面的代码中,我们定义了一个计算最大公约数的方法calculateGCD,并使用throws关键字声明该方法可能抛出NegativeNumberException异常。在方法的开头,我们检查传递给该方法的两个数是否为负数,如果是,就抛出一个新的NegativeNumberException异常。在该异常的构造函数中,我们传递一个错误消息作为参数,并调用父类的构造函数,将该错误消息传递给它。
在main方法中,我们调用calculateGCD方法,传递两个参数,其中一个为负数。由于该方法抛出了NegativeNumberException异常,我们使用try-catch块捕获该异常,并打印出错误消息。
阅读全文
相关推荐
![](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)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)