0

So what I'm working on right now should be pretty simple. I'm adding an item to an Arraylist, and if the item's name is equal to the name of another item in the Arraylist, it gets rid of one of the items and just adds the numItem value to the other item. So for example, if a player buys "guns", and the numItem variable is set to 1500, it's added to an arraylist. If they input "guns" again, and that numItem is 2500, I want to get rid of one of the elements in the arrayList and just set the numItem of the remaining to 4000.

public void addItem(Item item)
{
    for(int i = 0; i < this.ownedItems.size(); i++)
    {
        if(item.getName() == this.ownedItems.get(i).getName())
        {
            item.setNumItem(item.getNumItem() + this.ownedItems.get(i).getNumItem());
            this.ownedItems.remove(this.ownedItems.get(i));
        }
    }
    this.ownedItems.add(item);
}
Fábio Nascimento
  • 2,644
  • 1
  • 21
  • 27
dtg108
  • 25
  • 4

1 Answers1

1

Hey you did not tag the language you are programming in, but i assume you use java. Your code should do the trick, if you change your string compare.

If you compare Strings by stating string1 == string2 things will not go the way you would expect. Instead use string1.equals(string2)

You should read up on String compare: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

How do I compare strings in Java?

If you use C# i think the same principal more or less holds:

C# difference between == and Equals()

So change

if(item.getName() == this.ownedItems.get(i).getName())

into

if(item.getName().equals(this.ownedItems.get(i).getName()))
Stephan Hogenboom
  • 1,543
  • 2
  • 17
  • 29