可以使用try-catch语句来捕获ValueException异常,并进行处理。以下是一个示例代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a, b;
System.out.print("请输入两个整数,用空格隔开:");
a = scanner.nextInt();
b = scanner.nextInt();
try {
int gcd = getGreatestCommonDivisor(a, b);
System.out.printf("%d和%d的最大公约数为:%d", a, b, gcd);
} catch (Exception e) {
System.out.println("输入不合法,请输入两个非零整数!");
}
}
public static int getGreatestCommonDivisor(int a, int b) throws Exception {
if (a == 0 || b == 0) {
throw new Exception("输入不合法");
}
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
}
在示例代码中,首先通过Scanner类获取输入的两个整数a和b,并传入getGreatestCommonDivisor方法中计算最大公约数。当输入的整数中有一个为0时,getGreatestCommonDivisor方法会抛出一个自定义的Exception异常,表示输入不合法。在main方法中使用try-catch语句捕获异常,并输出'输入不合法,请输入两个非零整数!”。除了ValueException,其他的异常也可以用这种方式来捕获和处理。
上一篇:编写器和Kotlin版本兼容性
下一篇:编写确认对话框(是/否)