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

Java中如何找出数组中最贵与最便宜的UAV?问题排查与修复

问题分析与修复方案

你的代码核心问题是混淆了索引和价格的对比逻辑,同时初始化参数设置错误,导致价格比较完全失效:

1. 核心错误点

  • mostExpensive 和 leastExpensive 变量存储的是数组索引,但你拿UAV的价格(Double类型)直接和索引的整数值对比,完全不符合逻辑。比如:
    • 初始 leastExpensive = 1000000000,第一个UAV价格43 ≤ 1e9,所以记录索引0;后续UAV价格5和当前leastExpensive的数值0对比时,5 ≤ 0不成立,因此永远不会更新最便宜的索引。
    • mostExpensive 初始值为-1,后续拿价格和索引数值对比,会错误地把价格大于当前索引值的UAV当成更贵的,逻辑完全混乱。
  • 数组为空判断后没有终止方法,会继续执行循环导致NullPointerException。

2. 修复后的代码

public static void findLeastAndMostExpensiveUAV(FlyingObjects[] flyingObjects) {
    // 初始化最贵/最便宜的UAV索引和对应价格
    int mostExpensiveIndex = -1;
    double mostExpensivePrice = Double.MIN_VALUE;
    int leastExpensiveIndex = -1;
    double leastExpensivePrice = Double.MAX_VALUE;
    boolean hasUav = false;

    if (flyingObjects == null || flyingObjects.length == 0) {
        System.out.println("There is no UAV");
        return; // 终止方法,避免后续空指针
    }

    for (int i = 0; i < flyingObjects.length; i++) {
        if (flyingObjects[i] instanceof Uav) {
            Uav currentUav = (Uav) flyingObjects[i];
            double currentPrice = currentUav.getPrice();
            hasUav = true;

            // 更新最贵UAV
            if (currentPrice > mostExpensivePrice) {
                mostExpensivePrice = currentPrice;
                mostExpensiveIndex = i;
            }
            // 更新最便宜UAV
            if (currentPrice < leastExpensivePrice) {
                leastExpensivePrice = currentPrice;
                leastExpensiveIndex = i;
            }
        }
    }

    if (!hasUav) {
        System.out.println("There is no UAV");
    } else {
        System.out.println("\nInformation about the most expensive UAV: \n" + flyingObjects[mostExpensiveIndex] + "\n");
        System.out.println("Information about the least expensive UAV: \n" + flyingObjects[leastExpensiveIndex]);
    }
}

3. 关键修复说明

  • 拆分索引和价格变量:用mostExpensivePrice和leastExpensivePrice存储当前对比的价格,mostExpensiveIndex和leastExpensiveIndex存储对应数组索引,确保对比逻辑是价格和价格比。
  • 修正初始化值:用Double.MIN_VALUE作为最贵价格的初始值(确保第一个UAV的价格必然大于它),Double.MAX_VALUE作为最便宜价格的初始值(确保第一个UAV的价格必然小于它)。
  • 空数组判断后添加return:避免空指针异常。
  • 简化hasUav的赋值逻辑:只要遇到UAV就设为true,无需条件判断。

测试验证

用你提供的测试数组:

  • 最便宜的UAV是test[2](价格5)
  • 最贵的UAV是test[1](价格780000)
    修复后的代码能正确输出这两个结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:45:34