Reputation: 11
I have this array
public static ArrayList<String> inventory = new ArrayList<String>();
and have the players items stored inside of it.
I want to add a feature in the shop class that will sell everything but the pickaxe, how can I create a loop to check if theres something in the array other than "pickaxe" and if there is to remove it?
To remove I have a void
public void removeAllInventory() {
inventory.clear();
}
or
public void removeInventory(String item) {
inventory.remove(item);
}
Could I just edit the removeAllInventory to ignore the pickaxe and make a new void called removeAllShop or something? If so what would go in that void?
This is where I need to put it in:
else if (input.input.equalsIgnoreCase("all")) {
}
Upvotes: 0
Views: 340
Reputation: 2104
You shouldn't edit removeAllInventory()
to remove everything but the pickaxe. Its name would no longer make sense, and it seems a reasonable routine to keep around.
But you could add a new method, removeAllInventoryExcept(String item)
, that removes everything but the given the item.
Hope this helps.
EDIT: In attempt to beef up this answer, I'd also like to suggest the "out of the box" solution of:
public void removeAllInventoryExcept(String item) {
ArrayList<String> newInv = new ArrayList<String>();
newInv.add(item);
inventory = newInv;
}
This avoids the costly iteration and string comparisons.
Upvotes: 1
Reputation: 16526
for (String item : inventory) {
if (!"pixckaxe".equalsIgnoreCase(item)) {
inventory.remove(item);
}
}
Upvotes: 0
Reputation: 576
I'm assuming all of the items in the inventory are an ancestor of an item class, and not just a String.
You could loop through the ArrayList, getting the names of each element and comparing it with the pickaxe name.
or
You could loop through the ArrayList and checking if each item is an instanceof
pickaxe, and if it is not, remove it from the ArrayList
edit* It seems you specified the ArrayList is of type String, so ignore the second option
Upvotes: 0
Reputation: 4784
Loop over the list, check if if each element is equal to pickaxe, and remove it if it not.
Iterator<String> i = inventory.iterator();
while (i.hasNext()) {
if (i.next().equalsIgnoreCase("pickaxe"))
i.remove()
}
Upvotes: 2