Reputation: 311
What I need to do is find the inventory item with the lowest cost from an array list. If there are none, return "N/A". So I can't really figure out how to find the smallest value out of all the inventory item costs. This is what I have so far. My plan was to set cost equal to the first inventory item and cycle through each item checking if it's cost is less but I'm confused on how to do that or if that is even the correct way of doing it.
EDIT: We have not covered for loops yet so I cannot use them. I can only use while loops
public InventoryItem itemWithLowestCost() {
if (inventoryList.size() > 0) {
int i = 0;
while (i < inventoryList.size()) {
double cost = inventoryList.get(i).getCost();
if (cost < )
}
}
else {
return "N/A";
}
}
Here is my InventoryItem constructor. I'm not sure if this is needed to understand the above code but here it is anyway
public InventoryItem(String descriptionIn, double costIn, double percentDepreciatedIn) {
description = descriptionIn.trim();
cost = costIn;
percentDepreciated = percentDepreciatedIn;
}
Upvotes: 2
Views: 3459
Reputation: 726489
You can do it by checking the length to be non-zero, then picking the cost of element zero as "tentative best", and comparing it to costs of other elements on the list:
if (inventoryList.size() > 0) {
int best = 0;
int i = 1;
while (i < inventoryList.size()) {
double cost = inventoryList.get(i).getCost();
if (cost < inventoryList.get(best).getCost()) {
best = i;
}
i++;
}
return inventoryList.get(best);
} else {
return "N/A";
}
Upvotes: 2
Reputation: 793
You could use a comparitor to sort the inventory by cost, lowest to highets.
public InventoryItem itemWithLowestCost(Collection<InventoryItem> inventory) {
if(inventory != null && !inventory.isEmpty()) {
Collections.sort(inventory, new Comparator<InventoryItem>() {
@Override
public int compare(InventoryItem i1, InventoryItem i2) {
return i1.getCost() - i2.getCost();
}
});
return inventory.get(0);
}
return null;
}
Upvotes: 2
Reputation: 201429
You can do it with a O(n)
loop
public InventoryItem itemWithLowestCost() {
int size = (inventoryList == null || inventoryList.isEmpty()) ?
0 : inventoryList.size();
InventoryItem min = (size > 0) ? inventoryList.get(0) : null;
for (int i = 1; i < size; i++) {
InventoryItem ii = inventoryList.get(i);
if (ii.getCost() < min.getCost()) min = ii;
}
return min;
}
Note: That you can't return a String
N/A as an InventoryItem
instance (so this returns null
).
Upvotes: 2