1、【ArrayIndexOutOfBoundsException异常】编写一个程序,创建一个由100个随机选取的整数构成的数组;提示用户输入数组下标,然后显示元素的值,如果指定的下标越界,显示消息out of bounds。
2、【OutOfMemoryError错误】编写一个程序,它能导致JVM抛出一个OutOfMemoryError,然后捕获并处理这个错误。
//1
package shiyan6;
import java.util.Scanner;
public class demo2 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
boolean inputIndex= true;
int[]shuzu=new int[100];
//随机生成数字存入数组
for (int i=0;i<100;i++){
shuzu[i] = new java.util.Random().nextInt(100);
}
do{
try {
System.out.println("Please in put the index of the shuzu[0-100]:");
int index = input.nextInt();
System.out.println(shuzu[index]);
inputIndex= false;//输出之后退出
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("out of bounds!");
System.out.println("Please input again,index must be inputed from (0-100)");
}
}
while (inputIndex);
}
}
//2 方法一 不断输入数组的长度大小(在int范围之内),直到数组长度太大爆了
package shiyan6;
import java.util.Scanner;
public class demo3 {
public static void main(String[] args) {
boolean Stop =true;
do{
try {
System.out.println("Input an integer in of the range of (-2147483647~2147483647)");
Scanner input = new Scanner(System.in);
int len = input.nextInt();
int largArray[] = new int[len];
Stop = false;
} catch (OutOfMemoryError e) {
System.out.println("OutOfMemoryError !");
}
}while(Stop);
}
}
//2 方法二 直接产生一个最大的int 类型的整数直到数组长度爆了
package shiyan6;
import java.util.Scanner;
public class demo3 {
public static void main(String[] args) {
try {
int len = Integer.MAX_VALUE;
int largArray[] = new int[len];
System.out.println(len);
} catch (OutOfMemoryError e) {
e.printStackTrace();
System.out.println("Please input the munber of the array you want(lpease input small):");
Scanner input = new Scanner(System.in);
int len2 = input.nextInt();
System.out.println("The maxindex of the array you input is:"+len2);
}
}
}
这些实验可以灵活变通,因为有挺多种方式写的,重要在于捕获与处理的过程,生成随机付给数组的代码也可以是:Array[i] = (int)(System.currentTimeMillis()),即利用产生系统的时间数并转化为整形,只是他们的范围太近了不好区分。初学者的看法,期待指正。