我正在尝试查找数组列表(iList)中的最小值。数组列表包含多个项目(InventoryItem),每个项目都有自己的描述、成本等。我需要找到最小的成本,并返回成本最小的项目。另外,我必须使用 while 循环而不是 for 。这是到目前为止我的代码:
public InventoryItem itemWithLowestCost() {
int index = 0;
double smallest = 0;
while (index < iList.size()) {
if (!(smallest < iList.get(index).getCost())) {
smallest = iList.get(index).getCost();
}
if (iList.get(index).getCost() == smallest) {
return //what to put here? ;
}
index++;
}
}
最佳答案
这非常简单。存储当前最低的值,迭代,如果有较小的值,则保存它。最后返回当前最小的。
public InventoryItem itemWithLowestCost() {
InventoryItem smallest = iList.get(0);
for (int i=1;i<iList.size();i++) {
if(iList.get(i).getCost() < smallest.getCost()) {
smallest = iList.get(i);
}
}
return smallest;
}
如果你需要使用 while 循环,那么只需使用一个伪装的 for 循环;)
public InventoryItem itemWithLowestCost() {
InventoryItem smallest = iList.get(0);
int i = 1;
while (i<iList.size()) {
if(iList.get(i).getCost() < smallest.getCost()) {
smallest = iList.get(i);
}
i++;
}
return smallest;
}
关于java - 查找数组列表中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153095/