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

Java中用do-while循环检查数组触发ArrayOutOfBoundsException求助

解决ArrayOutOfBoundsException异常及代码逻辑问题

一、异常根源与核心问题

  • 数组越界直接触发点:dognames[dogs] 完全错误。Java数组下标从0开始,长度为dogs的数组,最大有效下标是dogs-1,访问dognames[dogs]必然抛出ArrayOutOfBoundsException。更关键的是,这里逻辑跑偏了——你需要的是接收用户输入的查询关键词,不是直接访问数组的越界位置。
  • while循环语法错误:while((!"quit".equals(dognames[dogs]))); 末尾的分号让循环体变成空语句,后面的代码块和这个循环毫无关联,完全达不到你循环查询的目的。
  • 比较逻辑失效:dognames[index].equals(dognames) 是把字符串和数组对象做比较,永远不会返回true,导致查询逻辑彻底没用。
  • 输出错误:System.out.println(dognames) 打印的是数组的内存地址,不是狗的实际信息。

二、修复后的完整代码

针对“循环查询狗名,输入quit退出,最后计算平均体重”的需求,修复后的代码如下:

import java.util.Scanner;

public class DogManager {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("How many dogs?");
        int dogs = input.nextInt();
        input.nextLine(); // 读取换行符,避免后续输入被跳过

        String[] dogNames = new String[dogs];
        Double[] dogWeights = new Double[dogs];

        // 录入狗的信息
        for (int i = 0; i < dogs; i++) {
            System.out.println("Enter dog name and weight: ");
            String[] info = input.nextLine().split(" ");
            dogNames[i] = info[0];
            dogWeights[i] = Double.parseDouble(info[1]);
        }

        // do-while循环实现查询功能
        String query;
        do {
            System.out.println("Enter a dog name to query (or 'quit' to exit):");
            query = input.nextLine().trim();
            if ("quit".equals(query)) {
                break;
            }

            boolean found = false;
            int index = 0;
            while (!found && index < dogNames.length) {
                if (dogNames[index].equals(query)) {
                    found = true;
                } else {
                    index++;
                }
            }

            if (found) {
                System.out.printf("Dog: %s, Weight: %.2f%n", dogNames[index], dogWeights[index]);
            } else {
                System.out.println("Error: Dog not found");
            }
        } while (!"quit".equals(query));

        // 计算并输出平均体重
        double sum = 0;
        for (double weight : dogWeights) {
            sum += weight;
        }
        double average = sum / dogWeights.length;
        System.out.printf("Average dog weight: %.2f%n", average);

        input.close();
    }
}

三、关键修复说明

  1. 修正数组访问逻辑:去掉dognames[dogs]的错误访问,改为接收用户输入的查询字符串query。
  2. 修复循环语法:用do-while循环实现“先执行查询,再判断是否退出”的逻辑,同时去掉原循环末尾的多余分号。
  3. 修复比较逻辑:将dognames[index].equals(dognames)改为dogNames[index].equals(query),正确匹配用户查询的狗名。
  4. 优化输入处理:使用nextLine()读取整行输入,解决next()/nextDouble()留下的换行符导致后续输入异常的问题。
  5. 修正输出内容:用printf()格式化输出狗的信息和平均体重,避免打印数组内存地址。
  6. 资源清理:添加input.close()关闭扫描器,避免资源泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:55:32