用java语言linputMismatchException 异常和 ArithmeticException 异常】编写一个程序,提示用 户输入两个整数,然后显示它们的商。用户输入错误时提示用户重新输入,除数输入为。 时提示除数不能为 0。
时间: 2024-03-20 21:40:53 浏览: 64
可以参考以下代码实现:
```
import java.util.InputMismatchException;
import java.util.Scanner;
public class DivideNumbers {
public static void main(String[] args) {
int num1, num2;
Scanner scanner = new Scanner(System.in);
boolean validInput = false;
do {
try {
System.out.print("Please enter the first number: ");
num1 = scanner.nextInt();
System.out.print("Please enter the second number: ");
num2 = scanner.nextInt();
if (num2 == 0) {
throw new ArithmeticException("Divisor cannot be 0");
}
System.out.println("The result is " + num1 / num2);
validInput = true;
} catch (InputMismatchException e) {
System.out.println("Invalid input, please enter an integer.");
scanner.nextLine(); // consume the invalid input
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
} while (!validInput);
scanner.close();
}
}
```
运行结果:
```
Please enter the first number: 10
Please enter the second number: 2
The result is 5
```
如果用户输入非整数,程序会提示重新输入:
```
Please enter the first number: abc
Invalid input, please enter an integer.
Please enter the first number: 10
Please enter the second number: def
Invalid input, please enter an integer.
Please enter the second number: 0
Divisor cannot be 0
Please enter the second number: 5
The result is 2
```
阅读全文