gpt4 book ai didi

java - 查找 ArrayList 中与常量相比差异最小的元素

转载 作者:行者123 更新时间:2023-12-02 02:15:03 26 4
gpt4 key购买 nike

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

在此代码中,变量 boxes = 5,任何具有 boxCapacity >=box 的元素都会添加到 ArrayList 中。从该列表中,应使用 boxCapacityboxes 最接近的那个。我可以选择那些大于 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com