(ArraylndexOutBoundsExcepfion 异常)编写一个满足下面要求的程序:
1.创建一个由 100 个随机选取的整数构成的数组。
2.提示用户输人数组的下标,然后显示对应的元素值。如果指定的下标越界,就显示消息 Out of Bounds.
package Homework3;
import java.util.Random;
import java.util.Scanner;
public class ArrayIndexOutBoundsException {
public static void main(String[] args) {
int[] Array = new int[100];
for (int i = 0; i < 100; i++) {
Array[i]=(int)(Math.random()*100);
}
System.out.print("请输入索引(1~100):");
Scanner input = new Scanner(System.in);
int index = input.nextInt();
ExceptionTest(Array, index);
input.close();
}
// 将异常处理的部分提取到函数中
public static void ExceptionTest(int[] Array, int index) {
try {
System.out.println("数组中第" + index + "位是" + Array[index - 1]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("异常抛出:" + e);
}
}
}