课题要求:
从命令行输入5个整数,放入一整型数组,然后打印输出。要求:
如果输入数据不为整数,要捕获输入不匹配异常,显示“请输入整数”;如果输入数据多余5个,捕获数组越界异常,显示“请输入5个整数”。
无论是否发生异常,都输出“感谢使用本程序!”
代码展示:
package shuru;
import java.util.*;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner sc=new Scanner(System.in);
int[] a=new int[5];
System.out.println("请输入:");
try{
for(int i=0;i<6;i++){
if(i==5)
throw new Exception("请输入5个整数");
a[i]=sc.nextInt();
}
}catch(InputMismatchException e){
System.out.println("请输入整数");
}catch(Exception e){
e.getMessage();
e.printStackTrace();
}
finally{
sc.close();
System.out.println("感谢使用本程序!");
}
}
}
结果: