【问题标题】:Having a hard time finding the minimum price in an array of objects很难在一组对象中找到最低价格
【发布时间】:2019-12-02 22:55:33
【问题描述】:
class FindMinTester1 extends Vehiclehw {

    Vehiclehw [] myVehicles = new Vehiclehw[100]; 

    public static double findMin (Vehiclehw[] theVehicles) { 

        int min = 0;

        for(int i = 1; i < Vehiclehw.length-1; i++) {
            if(Vehiclehw[i].getprice() < min)
                min = Vehiclehw[i].getprice;
        }
        return Vehiclehw;
    }
}

// 所以我理解这个问题有点模糊,但基本上我有一个名为 Vehiclehw 的超类,它有一个价格,在这个类中,我试图在 100 个元素的数组中找到最低价格。我知道没有声明任何对象,但我或多或少只需要知道在给定问题的情况下我将如何编写此方法。我得到的只是前两行。任何指导将不胜感激。

【问题讨论】:

  • 如果你从零开始min,价格会比以往更低吗?
  • int min = Vehiclehw[0].getprice();....return min;.
  • @CoolMind 运行良好,直到 theVehicles 为空,然后我们就有了 AIOOBE。
  • @ggorlen,是的。当我们讨论时,有人复制了我们的解决方案。 :)
  • @ArvindKumarAvinash,谢谢!我也看了你的简介,发现你很受欢迎。很高兴听到你的声音!

标签: java arrays object


【解决方案1】:

按如下方式进行:

class FindMinTester1 extends Vehiclehw {

    Vehiclehw[] myVehicles = new Vehiclehw[100];

    public static double findMin(Vehiclehw[] theVehicles) {
        if (theVehicles.length == 0){
            return (-Double.MAX_VALUE);
        }

        double min = theVehicles[0].getprice();

        for (int i = 1; i < theVehicles.length; i++) {
            if (theVehicles[i].getprice() < min)
                min = theVehicles[i].getprice();
        }
        return min;
    }
}

说明:

  1. 假设数组中只有一个价格。在这种情况下,它也将是最低价格。因此,您应该始终将第一个价格分配给变量min,然后将其与下一个价格进行比较。如果下一个价格小于min 的值,则将该值分配给min。对列表中的所有价格重复此操作。请注意,由于i &lt; theVehicles.length - 1,您的循环会在一个仍有待比较的元素处终止。应该是i &lt; theVehicles.length
  2. 您的另一个错误是在要求返回最低价格(存储在min)时返回数组本身。
  3. 您必须考虑的第三件事是将min 声明为double 而不是int
  4. 返回一些值,例如double 的最小值,以避免程序因空数组而崩溃。
  5. 您已经编写了return Vehiclehw,其中Vehiclehw 是超类的名称。这是错误的;你应该返回一个值。

【讨论】:

  • 这似乎是正确的,我唯一的问题是它一直说 Vehiclehw 无法解析为变量,并且在 if 语句的 .length 部分也给了我一个错误。但我不知道为什么
  • 是的,这确实对我有用,非常感谢您的帮助,谢谢。
猜你喜欢
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 2014-03-06
  • 1970-01-01
相关资源
最近更新 更多