编写Main类,用scanner类输入两个整数a,b;采用Java异常处理机制(try...catch 语句)处理以下异常: 1. 如果a,b不是整数(InputMismatchException),输出java.util.InputMismatchException was thrown 2. 如果b是零(ArithmeticException),输出:java.lang.ArithmeticException was thrown 3. 无异常抛出,则打印输出a/b.
时间: 2024-01-21 11:18:22 浏览: 85
以下是代码实现:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("请输入整数a:");
int a = scanner.nextInt();
System.out.print("请输入整数b:");
int b = scanner.nextInt();
System.out.println("a/b=" + (a / b));
} catch (InputMismatchException e) {
System.out.println("java.util.InputMismatchException was thrown");
} catch (ArithmeticException e) {
System.out.println("java.lang.ArithmeticException was thrown");
}
}
}
```
当输入的a或b不是整数时,会抛出`InputMismatchException`异常,我们在`try...catch`语句块中捕获该异常并输出提示信息。
当输入的b为零时,会抛出`ArithmeticException`异常,同样在`try...catch`语句块中捕获该异常并输出提示信息。
如果没有异常抛出,则按照题目要求输出`a/b`的结果。
阅读全文