Steve the Maker
Steve the Maker

Reputation: 621

How can I use a map for calculations?

I'm working on a program for class. Using a TreeMap to store IDs (String - Key) and earnings amounts (double - value). I'm importing the values from a text file using a Scanner. My problem at the moment is that I need the values to accumulate rather than overwriting with the last value read. So my question is how do you use a Map to do calculations like that? Any help would be appreciated.

Upvotes: 1

Views: 142

Answers (3)

Kashyap
Kashyap

Reputation: 17451

There is no implicit functionality in Map. Idea behind your homework assignment is for you to learn how to insert, find, get and replace to/from a Map. There are functions for each of these and ou should use all to get this done.

Upvotes: 3

JProgrammer
JProgrammer

Reputation: 1135

1) Check whether value with same key exists in the map 2) If it exists then read it and add the currently read value. Put it back into map

Upvotes: 1

Laf
Laf

Reputation: 8205

When adding a new value to your map, if the key already exists, you can get the associated value, add the new value to it, and put it back into the map. Example:

// Assuming that key and value were read from your file, and that
// myMap is declared as "Map<String, Double>"
if (myMap.containsKey (key)) {
    double oldValue = myMap.get (key);
    value += oldValue;
}

myMap.put (key, value);

Upvotes: 1

Related Questions