ARTICLE AD BOX
The game has a repair task. There is a List of required items, and when the method is called, it iterates over the inventory and if a match is found, it adds the item to the list "toRemove" and after the loop it removes those items from the players inventory as well as from required items. If I checked correctly, this works if there is only one item. Now I don't know how to handle the case of duplicates. In this implementation, it removes all items from requiredItems (and probably also from the players inventory) of the same name.
public boolean tryRepair(List<Item> inventory) { List<Item> toRemove = new ArrayList<>(); for (Item item : inventory) { for (RepairItem required : requiredItems) { if (item.getName().equals(required.getName())) { toRemove.add(item); repairedItems.add(required); break; } } } inventory.removeAll(toRemove); requiredItems.removeAll(toRemove); if (repairedItems.size() < requiredItems.size()) { completed = false; } else { completed = true; } return true; }Now what approach can I take to handle duplicates?
** Added the item class
public abstract class Item { private String name; private String description; public Item(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } }New contributor
Enes is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
6
