Java 输入数据 异常处理

从命令行输入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("感谢使用本程序。");  
        }  
    }  
}  

 

运行结果:

 

 

posted @ 2017-12-10 21:34  浅笑Cc。  阅读(4162)  评论(0编辑  收藏  举报