题目:
从命令行输入5个整数,放入一整型数组,然后打印输出。要求:
如果输入数据不为整数,要捕获输入不匹配异常,显示“请输入整数”;如果输入数据多余5个,捕获数组越界异常,显示“请输入5个整数”。
代码:
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestArrayException {
public static void main(String[] args) {
int a[] = new int[5];
System.out.println("请输入5个数,结束后输入0打印数组:");
Scanner in = new Scanner(System.in);
try{
int i=0;
if(in.hasNextInt()){
for(i=0;i<a.length;i++)
a[i] = in.nextInt();
int b=in.nextInt();
if(b==0){
System.out.println("数组为:");
for(int j=0;j<a.length;j++)
System.out.println(a[j]);
}
else
throw new ArrayIndexOutOfBoundsException();
}
else
throw new InputMismatchException();
}catch(InputMismatchException e1){
System.err.println("请输入整数!");
e1.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e2){
System.err.println("请输入5个数!");
e2.printStackTrace();
}finally{
System.out.print("感谢使用本程序!");
}
}
}
运行图: