從命令行輸入5個整數,放入一整型數組,然后打印輸出。要求:
如果輸入數據不為整數,要捕獲輸入不匹配異常,顯示“請輸入整數”;如果輸入數據多余5個,捕獲數組越界異常,顯示“請輸入5個整數”。
無論是否發生異常,都輸出“感謝使用本程序!”
import java.util.InputMismatchException; import java.util.Scanner; public class test { public static int[] number; public static void main(String[] args) { number=new int[5]; Scanner input=new Scanner(System.in); try { for(int i=0;i<6;i++) { if(i==5) throw new Exception("請輸入5個整數。"); number[i]=input.nextInt(); } } catch (InputMismatchException e) { System.err.println("請輸入整型數據。"); }catch (Exception e) { e.getMessage(); e.printStackTrace(); }finally { input.close(); System.out.println("感謝使用本程序。"); } } }
運行結果:

