0
public void addItem(String itemName,int numItemAdd) {

    HashMap <String,Integer> items = new HashMap<String,Integer>();
            
    int totalval;
    
    totalval =+ numItemAdd;
    
    items.put(itemName,totalval);
    
}

I am new to HashMaps. I am wanting to add the integers to the specific itemName. For example, addItem("socks",100); addItem("socks",200). Whenever I do this, instead of getting 300 I only get 200. I know that put() replaces the last value used, but I do not know how to add the numbers so that I can get 300 instead of having the last value used.

ZDrop
  • 1
  • 1

1 Answers1

0

You can try this, it also manages the case when socks don't exist:

    private HashMap <String,Integer> items = new HashMap<String,Integer>();

    public static void main(String[] args) {
        Test test = new Test();
        test.addItem("socks", 100);
        test.addItem("socks", 200);
    }

    public void addItem(String itemName,int numItemAdd) {
        items.put(itemName,items.get(itemName) != null ? (items.get(itemName) + numItemAdd) : numItemAdd);
        System.out.println("Socks value:" + items.get(itemName));
    }
happy songs
  • 835
  • 8
  • 21