6-4 Java异常处理

前言

这道题好坑啊,想了好久,路过的大佬麻烦给彩笔我点个赞鼓励一下呗。

6-4 Java异常处理

分数 11

作者 zhengjun

单位 浙江传媒学院

设有一个整数数组a[], a有10个元素,其值依次为0到9。

从键盘输入整数i的值,求a[i]的倒数。

注意处理各种异常。发生异常后,根据不同的异常,输出警告。

提示:

需要考虑InputMismatchException、ArrayIndexOutOfBoundsException、ArithmeticException等多种异常。 

裁判测试程序样例:

import java.util.Scanner;
import java.util.InputMismatchException;
 
public class Main {
    public static void main(String[] args) {
        int[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
            
        /* 请在这里填写答案 */
    }
}

输入格式:

先输入一个整数n,表示有n组数据。

此后有n行,每行有一个整数i。

输出格式

正常情况下,输出1/a[i]的值(整数形式)。

如果发生InputMismatchException异常,输出“catch a InputMismatchException”。

如果发生ArrayIndexOutOfBoundsException异常,输出“catch a ArrayIndexOutOfBoundsException”。

如果发生ArithmeticException异常,输出“catch a ArithmeticException”。

输入样例:

4
1
10
0
a

输出样例:

1
catch a ArrayIndexOutOfBoundsException
catch a ArithmeticException
catch a InputMismatchException

 下面解析这道题

1. 第一个坑点在InputMismatchException类上,scanner输入的字符类型一直存放于Scanner中,在下一个循环中会直接读取缓冲区的内容并输出匹配异常

 2. 第二个坑点在题目要求了...等多种异常,也就是说要检测其他的错误异常(比如输入n时可能会出异常)。

考虑到以上两点,我们就很容易可以得到最后答案

Scanner s=new Scanner(System.in);
        int m=0;

        try{
            int n=s.nextInt();
            m=n;
        }catch(InputMismatchException ex){
            System.out.println("catch a InputMismatchException");
            System.exit(0);//结束程序
        }



        for(int j=0;j<m;j++){
            try{

                int k=s.nextInt();
                int b=1/a[k];
                System.out.println(b);
            }catch(InputMismatchException ex){
                //输入不匹配
                System.out.println("catch a InputMismatchException");
                s.nextLine();
                //接受存放于Scanner中的异常数据(包括空格),让他可以继续接受控制台输入的数据
               

            }catch(ArrayIndexOutOfBoundsException ex){
                //越界异常
                System.out.println("catch a ArrayIndexOutOfBoundsException");

            }catch(ArithmeticException ex){
                //算数异常
                System.out.println("catch a ArithmeticException");

            }catch(Error ex){
                System.out.println("error");

            }catch(Exception ex){
                System.out.println("Exception");

            }catch(Throwable ex){
                System.out.println("Throwable");

            }
        }

 参考资料

InputMismatchException输入类型异常,捕捉后,想要继续输入的方法

Java中使用nextLine输入数据时遇到InputMismatchException异常的解决办法

java中sc.next()与sc.nextLine()输入字符串的区别和注意事项

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cllsse

富✌您吉祥

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值