PTA 7-84 jmu-Java-06异常-01-常见异常 题解

题面:

自行编码产生常见异常。

main方法

事先定义好一个大小为5的数组。
根据屏幕输入产生相应异常。
提示:可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。

输入说明:

arr 代表产生访问数组是产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。
null,产生NullPointerException
cast,尝试将String对象强制转化为Integer对象,产生ClassCastException。
num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。
其他,结束程序。

输入样例:

arr 4
null
cast
num 8
arr 7
num a
other

输出样例:

java.lang.NullPointerException
java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
java.lang.NumberFormatException: For input string: "a"

解析:

本题核心思想在于构造异常抛出,据题意模拟即可。
主要需要使用的知识是,try catch 代码块与 Exception 捕获异常。

满分代码:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] array = new int[5];

        while (true) {
            String input = scanner.next();
            if(input.equals("other")) break;
            if (input.equals("arr")) {
                try {
                    int index = scanner.nextInt();
                    int d = array[index];
                } catch (Exception e) {
                    System.out.println(e);
                }
            } else if (input.equals("null")) {
                try {
                    String nullString = null;
                    nullString.length(); // 必然抛出NullPointerException
                } catch (Exception e) {
                    System.out.println(e);
                }
            } else if (input.equals("cast")) {
                try {
                    Object obj = "string";
                    Integer number = (Integer) obj; // 必然抛出ClassCastException
                } catch (Exception e) {
                    System.out.println(e);
                }
            } else if (input.equals("num")) {
                try {
                    String numberStr = scanner.next();
                    int number = Integer.parseInt(numberStr); // 可能抛出NumberFormatException
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }

        scanner.close();
    }
}
posted @ 2024-11-18 20:44  [丘李]Chilllee  阅读(124)  评论(0)    收藏  举报