编写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样例输入 6 3 样例输出 6/3=2
时间: 2024-01-21 10:18:28 浏览: 38
JAVA的异常处理机制
以下是代码实现:
```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 {
int a = scanner.nextInt();
int b = scanner.nextInt();
int result = a / b;
System.out.println(a + "/" + b + "=" + result);
} catch (InputMismatchException e) {
System.out.println("java.util.InputMismatchException was thrown");
} catch (ArithmeticException e) {
System.out.println("java.lang.ArithmeticException was thrown");
}
}
}
```
运行结果:
输入:
```
6 3
```
输出:
```
6/3=2
```
阅读全文