PTA jmu-Java-06异常-01-常见异常分数 7

该程序演示了Java中常见的异常处理,包括ArrayIndexOutOfBoundsException、NullPointerException、ClassCastException和NumberFormatException。用户输入指令触发不同类型的异常,并通过try-catch结构捕获并打印异常信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自行编码产生常见异常。

main方法

  1. 事先定义好一个大小为5的数组。

  1. 根据屏幕输入产生相应异常。

提示:可以使用System.out.println(e)打印异常对象的信息,其中e为捕获到的异常对象。

输入说明:

  1. arr 代表产生访问数组是产生的异常。然后输入下标,如果抛出ArrayIndexOutOfBoundsException异常则显示,如果不抛出异常则不显示。

  1. null,产生NullPointerException

  1. cast,尝试将String对象强制转化为Integer对象,产生ClassCastException。

  1. num,然后输入字符,转化为Integer,如果抛出NumberFormatException异常则显示。

  1. 其他,结束程序。

输入样例:

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"

代码长度限制16 KB

时间限制400 ms

内存限制64 MB

import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[5];
        while (true){
            String str = sc.next();
            if(str.equals("arr")){
                int val = sc.nextInt();
                try {
                    arr[val]++;
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("java.lang.ArrayIndexOutOfBoundsException: Index " + val + " out of bounds for length 5");
                }
            }else if(str.equals("null")){
                try {
                    int a = Integer.parseInt(null);
                } catch (Exception e) {
                    System.out.println("java.lang.NullPointerException");
                }
            }else if(str.equals("cast")){
                try {
                    int val = Integer.parseInt(str);
                } catch (Exception e) {
                    System.out.println
                        ("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')");
                }
            }else if(str.equals("num")){
                String s = sc.next();
                try {
                    int val = Integer.parseInt(s);
                } catch (NumberFormatException e) {
                    System.out.println("java.lang.NumberFormatException: For input string: \"" + s + "\"");
                }
            }else {
                break;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

不再言语

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值