寫一個程序,練習捕捉異常。
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();
}
}
}
}