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.

1
  • change "socks" after adding another, it will only add to the same key on the hash map Commented Apr 8, 2022 at 1:24

1 Answer 1

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));
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.