前言
这道题好坑啊,想了好久,路过的大佬麻烦给彩笔我点个赞鼓励一下呗。
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输入类型异常,捕捉后,想要继续输入的方法