我试图让这段代码确定哪个元素的值最接近常量。

在此代码中,变量boxes = 5(具有boxCapacity >= boxes的任何元素)都将添加到ArrayList中。从该列表中,应使用与boxCapacity最接近的boxes。我可以选择大于boxes的那些,但是不能选择与最接近的boxCapacity的那些。

public void deliver(double miles, int boxes) {
    for (int i = 0; i < cars.size(); i++){
        if (cars.get(i).getBoxCapacity() >= boxes){
            deliveryCars = new ArrayList<Car>();
            deliveryCars.add(cars.get(i));
            smallest = deliveryCars.get(0).getBoxCapacity();
            for(j = 0; j < deliveryCars.size(); j++){
               if (deliveryCars.get(j).getBoxCapacity() < smallest) {
                  smallest = deliveryCars.get(j).getBoxCapacity();
                  k++;
               }
            }
        }
    }
    System.out.println("Delivering with " + deliveryCars.get(k).getPlate());
}


我试图制作一个新列表,但尚未制定出来。

最佳答案

您可以将代码简化为类似如下的形式

public void deliver(double miles, int boxes){
        // check if there are cars availible
        if (!cars.isEmpty()) {
            // assume that first car in a list is best for delivery
            int smallest = cars.get(0).getBoxCapacity();
            Car deliveryCar = cars.get(0);
            // iterating over all cars in a list
            // but still compares to the first car in a list
            for (Car car : cars) {
                if (car.getBoxCapacity() >= boxes
                        && car.getBoxCapacity() < smallest) {
                    deliveryCar = car;
                }
            }
            System.out.println("Delivering with " + deliveryCar.getPlate());
        }
    }

关于java - 与常量比较时,找到ArrayList中具有最小差异的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49419177/

10-09 20:47