00:00
00:00
Newgrounds Background Image Theme

Zpredojev just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

Inventory System Help please

419 Views | 2 Replies
New Topic Respond to this Topic

Inventory System Help please 2016-04-21 15:20:09


I'm trying to make this method in Java that adds an item to your inventory.
The bags[] array holds the names to the items and the items[] array hold the amount of items that correlates with that name.
I'm trying to make it so that if the itemName of the item being added already exists in the bags[] array, only the amount is added to that correlating index.

public class Inventory {
	static String[] bags = {"Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty","Empty"};
	static int[] items = {0,0,0,0,0,0,0,0,0,0};
	static int i = 0; 							//Iterate for loop//
	static int x = 0;
	static int y = 0;//Change open bag slot//
	String itemName = "";
	int amount = 0;
	
	public static void addInv(String itemName, int amount){
	
		bags[x] = itemName;
		items[x] = items[x] + amount;
		x++;
		
		System.out.println("BAG UPFATE");
		for(i = 0; i<9; i++){
			System.out.println(bags[i] +"\t"+ items[i]);
		}
	}
}

Instead what I have is; adding each new itemName to a new index of the array, I've tried checking if

if(itemName == bags[x]){
			items[x] = items[x] + amount;
		}

to only add the amount to that position in the array but I keep getting really confused. I was wondering if anyone here could save me. haha

Response to Inventory System Help please 2016-04-21 18:34:58


It would make more sense to store these in an associative array, which can achieved with Java's Map interface. The documentation also has lots of information on Map.

So, something like this:

public class Inventory {
    static Map<String,Integer> bags = new HashMap<String,Integer>();
    
    public static void addInv(String itemName, Integer amount) {
        bags.put(itemName, amount);

        System.out.println("BAG UPDATE");
        for (String name : bags.keySet()) {
            System.out.println(name +"\t"+ bags.get(name));
        }
    }
}

Example of this.

I'm not familiar with Java, so this might not be the best way to do it, but it will work and will be easier than what you're doing now.

Response to Inventory System Help please 2016-04-21 22:27:51


At 4/21/16 06:34 PM, Diki wrote: It would make more sense to store these in an associative array, which can achieved with Java's Map interface. The documentation also has lots of information on Map.

I'm not familiar with Java, so this might not be the best way to do it, but it will work and will be easier than what you're doing now.

Thanks! I don't know much about HashSet but if your suggesting it I'll do some research. haha