You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中用try-catch实现数组元素查找并避免索引越界

完整解决方案

没问题!我帮你把代码补全并加上try-catch异常处理逻辑,完美解决输入超出数组范围的问题,完整可运行代码如下:

import java.util.Scanner;
import java.util.InputMismatchException;

public class UserInfoLookup {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String[] name = {"Lucas", "Vulnere"};
        int[] age = {15, 16};
        String answer = "";

        // 打印初始用户信息列表,方便用户查看有效ID范围
        System.out.println("ID\tNames\tAges");
        for (int i = 0; i < name.length; i++) {
            System.out.println((i + 1) + "\t" + name[i] + "\t" + age[i]);
        }

        // 循环查询,直到用户输入quit退出
        do {
            System.out.print("\n请输入要查询的ID(输入'quit'退出):");
            try {
                // 先判断输入是否为整数,避免输入非数字导致的异常
                if (input.hasNextInt()) {
                    int id = input.nextInt();
                    input.nextLine(); // 读取输入后的换行符,避免后续读取异常
                    int index = id - 1; // 转换为数组索引(ID从1开始,数组索引从0开始)
                    // 输出对应用户信息
                    System.out.printf("查询结果:ID=%d,姓名=%s,年龄=%d%n", id, name[index], age[index]);
                } else {
                    answer = input.nextLine();
                    // 处理非quit的无效输入
                    if (!answer.equalsIgnoreCase("quit")) {
                        System.out.println("⚠️ 请输入有效的数字ID,或者输入'quit'退出程序!");
                    }
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                // 捕获ID超出数组范围的异常
                System.out.printf("❌ 错误:输入的ID超出范围!当前有效ID是1到%d%n", name.length);
                input.nextLine(); // 清除错误输入,避免死循环
            } catch (Exception e) {
                // 捕获其他未知异常
                System.out.println("❌ 发生未知错误,请重试!");
                input.nextLine(); // 清除错误输入
            }
        } while (!answer.equalsIgnoreCase("quit"));

        input.close();
        System.out.println("👋 程序已退出!");
    }
}
关键逻辑说明
  • 初始列表打印:通过循环遍历数组,把数组索引+1作为ID,打印出所有用户的信息,让用户清楚知道有效ID的范围
  • 循环查询机制:用do-while循环实现多次查询功能,用户可以反复查询直到输入quit退出
  • 异常处理:
    • 捕获ArrayIndexOutOfBoundsException:当用户输入的ID转换为数组索引后超出数组长度时,提示用户ID无效
    • 额外处理非数字输入:判断输入是否为整数,避免InputMismatchException,同时引导用户输入正确内容
    • 通用异常捕获:处理其他未知异常,保证程序不会直接崩溃

内容的提问来源于stack exchange,提问作者Louise Kaithlyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:45:24