I have an inventory class that has an array of the class 'Item', called items. Within the Item class, I have an int called quantity to represent how many of the item that you get with each pickup. I haven't been able to figure out how to get the number of duplicate items within the array, so that I can multiply that by the getQuantity() method for that item and get the total quantity of the item that the player is carrying.
public class Inventory {
private Item[] items; //A private Item array, called items
private int firstFree;
private int quantity;
private WorldRenderer world;
/**
* CREATES THE INVENTORY AT A SIZE SPECIFIED IN THE PARATHENESIS
*/
public Inventory(int size) {
items = new Item[size];
firstFree = 0;
}
public int getItemCount() {
for (int i = firstFree; i < items.length; i++) {
if (items[i] != null) {
return items.length;
}
}
return 0;
}
public boolean add(Item item) {
if (firstFree == items.length) {
return false;
}
items[firstFree] = item;
for (int i = firstFree; i < items.length; i++)
if (items[i] == null) {
firstFree = i;
return true;
}
firstFree = items.length;
return true;
/**for (int i = 0; i < items.length; i++)
if (items[i] == null){
items[i] = item;
System.out.println("Item " + item.getName() + " added to inventory at index " + i); // TESTING
return true;
}
return false;
}**/
}
public Item get(int index) {
return items[index];
}
public void setQuantity(Item item, int quantity) {
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
items[i].setQuantity(quantity);
}
}
}
public void removeQuantity(Item item, int quantity) {
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
items[i].setQuantity(item.getQuantity() - quantity);
}
}
}
public int getQuantity(Item item) {
int quantity = 0;
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
quantity = items[i].getQuantity();
}
}
return quantity;
}
}
Perhaps there is a better way to go about creating an inventory for my particular problem?
EDIT: Trying the HashMap and getting an NPE at this line
if (items.containsKey(item)){
Integer previousQuantity = items.get(items);
items.put(item, ++previousQuantity); // NPE this line.
} else {
items.put(item, 1);
}
quantity += items[i].getQuantity();produce the expected result? If not, what is the expected result and what result are you currently getting?Itemis a duplicate? You don't seem to have any fields in place (such as a string with the name of theItem) that could make that determination.