A HashMap holds the points scored (value) for each player (key) in game 1. A sim
ID: 3693418 • Letter: A
Question
A HashMap holds the points scored (value) for each player (key) in game 1. A similar HashMap holds the points scored for each player in game 2. For example: Do the following: Create a package named. "prob2" and a class named, "Games". Write a method named getTotals that accepts two HashMaps as described above and returns a TreeMap of all the players that played in both games and the total number of points they got. For the example above, the result is: Write a main with the maps above, call getTotals, and print the resulting TreeMap as shown immediately above.Explanation / Answer
package prob2;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* @author srinu
*
*/
public class Game {
/**
* method to return treemap of all the players that played in both games and
* total number of points they got
*
* @param game1
* @param game2
* @return
*/
public static TreeMap<String, Integer> getTotals(
HashMap<String, Integer> game1, HashMap<String, Integer> game2) {
TreeMap<String, Integer> totalScore = new TreeMap<String, Integer>();
Set<String> intersectKeys = game1.keySet();
intersectKeys.retainAll(game2.keySet());
for (String key : intersectKeys) {
totalScore.put(key, game1.get(key) + game2.get(key));
}
return totalScore;
}
public static void main(String[] args) {
try {
// declare and initialize the game1 scores
HashMap<String, Integer> game1 = new HashMap<String, Integer>();
game1.put("Chen", 4);
game1.put("Allie", 9);
game1.put("Reece", 4);
game1.put("Skuye", 6);
game1.put("Meshel", 6);
// declare and initialize the game2 scores
HashMap<String, Integer> game2 = new HashMap<String, Integer>();
game2.put("Chen", 8);
game2.put("Zyrene", 4);
game2.put("Skuye", 2);
game2.put("Meshel", 3);
// calling gettotals() by passing game1 and game2
TreeMap<String, Integer> totalScores = getTotals(game1, game2);
// iterating totalScores
for (Map.Entry<String, Integer> entry : totalScores.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = "
+ entry.getValue());
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
OUTPUT:
Key = Chen, Value = 12
Key = Meshel, Value = 9
Key = Skuye, Value = 8
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.