java - 从 HashMap 计算平均分数
问题描述
我不确定如何将其放入代码中。我正在构建这个小代码块,其中通过构建一个新的具有相同键的两个 HashMap 给出两个数字的商,并将键和新数字放在那里。例如 HashMap1 有 {a=6} 而 HashMap2 有 {a=3}。然后 HashMap3 会放 {a=2}。这是我正在处理的代码。
/**
* Given a list of reviews from the file, this method computes the average score
* for each word in the reviews and stores that score in the wordValue HashMap,
* where the key is the word and the value is the average score.
*
* To get the average score, first compute the total score for a word and the
* number of times it appears.
*
* As a slight improvement, only store the word in wordValue if the score is not
* an average word - if the score is less than 1.75 or greater than 2.25.
*
* @param reviews An ArrayList of lines representing reviews. The first word in
* each line is a score.
*/
public void computeWordValue(ArrayList<String> reviews) {
// Initialize any needed HashMaps
HashMap<String, Integer> totalScores = new HashMap<>();
HashMap<String, Integer> wordCount = new HashMap<>();
// Compute the word total scores and counts using the appropriate method.
computeScoreAndCounts(reviews, totalScores, wordCount);
// Build a HashMap of average scores
HashMap<String, Double> avgScoresMap = new HashMap<>();//I'm assuming this is empty
for (String wordKey : reviews) {
if (avgScoresMap.containsKey(wordKey)) {
Double avgScore = (double) (totalScores.get(wordKey) / wordCount.get(wordKey)); //I think this is why it doesn't work
avgScoresMap.put(wordKey, avgScore);
}
}
System.out.println(avgScoresMap);
}
我不知道为什么这不起作用,它只打印出任何内容或“{}”。不要担心前两个 HashMap。关于,谢谢
解决方案
这是你的问题。
HashMap<String, Double> avgScoresMap = new HashMap<>();//I'm assuming this is empty
for (String wordKey : reviews){
if (avgScoresMap.containsKey(wordKey)) {
Double avgScore = (double) (totalScores.get(wordKey)
/ wordCount.get(wordKey)); // I think this is why it doesn't work
avgScoresMap.put(wordKey, avgScore);
}
}
正如你所说,哈希图是空的。所以它不能包含任何东西,所以你containsKey
失败了。因此,您永远不会在地图中放置任何东西。更改它以检查它是否不在地图中。
推荐阅读
- ios - 更新 iOS 应用内购买的流程是什么?
- magento2 - 在 Magento 2 中为不同的客户组自动更改商店视图
- excel - 工作表!C295 -> 公式错误:运算符“:”没有操作数
- c# - 缓存 SQL 数据有哪些选项?
- c - 函数文档缺少有关返回的指针为 NULL 或非 NULL 的信息。假设什么?
- linux - 在 CMake FetchContent_Declare 中添加 GIT_CONFIG 在 Linux 上失败
- asp.net - 变量不可见
- django - Django url 有 %20 个问题
- php - 当 2 个表同时插入 1 个函数时,运行时发生错误
- google-apps-script - 谷歌表格脚本仅适用于特定范围