1.编写一个程序满足下面要求的程序ArrayExceptionTest.java: 创建一个由100个随机选取的整数构成的数组 提示用户输入数组下标,然后显示对应的元素值 如果用户输入的不是一个可转化为整数的字符(抛出InputMismatchException),就显示消息” Incorrect input re-enter one integers number:”。要求用户重新输入。 如果用户输入的数字越界(抛出IndexOutOfBoundsException),就显示消息” Out of Bounds re-enter one integers number:”要求用户重新输入。
时间: 2024-02-24 15:56:26 浏览: 31
下面是一个满足要求的Java程序ArrayExceptionTest.java:
```java
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class ArrayExceptionTest {
public static void main(String[] args) {
int[] arr = new int[100];
Random rand = new Random();
for (int i = 0; i < 100; i++) {
arr[i] = rand.nextInt(1000);
}
Scanner input = new Scanner(System.in);
int index = -1;
while (true) {
System.out.print("Enter an index: ");
try {
index = input.nextInt();
System.out.println("The corresponding element value is " + arr[index]);
} catch (InputMismatchException e) {
System.out.println("Incorrect input, re-enter an integer: ");
input.nextLine();
} catch (IndexOutOfBoundsException e) {
System.out.println("Out of Bounds, re-enter an integer: ");
input.nextLine();
}
}
}
}
```
这个程序首先创建一个由100个随机选取的整数构成的数组。然后提示用户输入数组下标,如果用户输入的不是一个可转化为整数的字符,就显示消息” Incorrect input, re-enter an integer:”要求用户重新输入;如果用户输入的数字越界,就显示消息” Out of Bounds, re-enter an integer:”要求用户重新输入。如果输入正确,则输出对应的元素值。程序会一直运行,直到用户输入Ctrl+C结束程序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)