写一个程序,练习捕捉异常。
1、首先创建一个100个元素的数组,并用随机数填充该数组,类型随意。
2、提示用户输入一个下标,输出该下标对应的元素值。如果输入不是整数,输出“Input Mismatch.”并提示用户重新输入;如果下标越界,输出“Out of Bounds.”并提示用户重新输入;如果不是以上情况,程序输出元素值后正常结束。
3、代码不允许使用if语句,只能用异常捕捉实现上述功能。
import java.util.InputMismatchException;
import java.util.Scanner;
public class Exception {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
boolean mark=true;
int[]a=new int[100];
for(int i=0;i<100;i++){
a[i]=(int)(Math.random()*100);
}
while(mark){
try{
System.out.println("输入下标:");
int i=input.nextInt();
System.out.println(a[i]);
mark=false;
}catch(IndexOutOfBoundsException ex){
System.out.println("Error: Out of Bounds.");
System.out.println("Input Again: ");
input.nextLine();
}
catch(InputMismatchException ex){
System.out.println("Error: Input Mismatch.");
System.out.println("Input Again: ");
input.nextLine();
}
}
}
}