创建一个类MaxFactor; ②在类中定义一个方法,完成最大公约数的计算并声明该方法会抛出的异常,同时在该方法中手动抛出一个异常对象; ③在main方法中调用定义的方法,并捕获方法抛出规划的异常进行处理。
时间: 2024-02-01 07:14:08 浏览: 29
下面是实现代码:
```java
class MaxFactor {
public int calculate(int a, int b) throws IllegalArgumentException {
if (a <= 0 || b <= 0) {
throw new IllegalArgumentException("参数必须为正整数");
}
int max = Math.max(a, b);
int min = Math.min(a, b);
while (max % min != 0) {
int temp = max % min;
max = min;
min = temp;
}
return min;
}
}
public class Main {
public static void main(String[] args) {
MaxFactor maxFactor = new MaxFactor();
try {
int result = maxFactor.calculate(24, 36);
System.out.println("最大公约数为:" + result);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
```
在MaxFactor类中,我定义了一个calculate方法来计算最大公约数,并声明该方法会抛出IllegalArgumentException异常。在方法中,我使用了辗转相除法来计算最大公约数。如果传入的参数不是正整数,我就手动抛出一个IllegalArgumentException异常。
在main方法中,我创建了MaxFactor对象并调用了calculate方法。由于传入的参数是24和36,所以不会抛出异常,最后输出最大公约数为12。如果传入的参数是负数或0,就会抛出IllegalArgumentException异常,在catch块中捕获该异常并输出异常信息。