Reputation: 37
I'm trying to find the smallest value in an array list(iList). The array list contains multiple items (InventoryItem) each with their own description, cost, etc. I need to find the smallest cost, and return the item that has the smallest cost. Also, I have to use a while loop and not a for. Here is my code so far:
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++;
}
}
Upvotes: 0
Views: 3658
Reputation: 13596
This is pretty simple. Store the current lowest, iterate through, and if something is smaller, save that. At the end return the current smallest.
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;
}
If you need to use a while loop, then just use a disguised for loop ;)
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;
}
Upvotes: 4