设有一个整数数组a[], a有10个元素,其值依次为0到9。 从键盘输入整数i的值,求a[i]的倒数。 注意处理各种异常。发生异常后,根据不同的异常,输出警告。 提示:需要考虑InputMismatchException、ArrayIndexOutOfBoundsException、ArithmeticException等多种异常。
时间: 2023-07-16 14:16:02 浏览: 49
下面是一个Java程序实现:
```java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Scanner scanner = new Scanner(System.in);
try {
int i = scanner.nextInt();
if (i < 0 || i >= a.length) {
throw new ArrayIndexOutOfBoundsException("数组下标越界");
}
if (a[i] == 0) {
throw new ArithmeticException("除数为0");
}
double result = 1.0 / a[i];
System.out.println("a[" + i + "]的倒数是:" + result);
} catch (InputMismatchException e) {
System.out.println("输入格式有误");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界");
} catch (ArithmeticException e) {
System.out.println("除数为0");
}
}
}
```
程序首先定义了一个数组a,然后通过Scanner从键盘输入整数i。接着使用try-catch语句块处理可能出现的异常,如果输入格式有误,则捕获InputMismatchException异常;如果输入的i值超出了数组下标范围,则捕获ArrayIndexOutOfBoundsException异常;如果a[i]的值为0,则捕获ArithmeticException异常。在每个catch块中输出相应的警告信息。最后,如果没有发生异常,则输出a[i]的倒数。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)