首页 > 解决方案 > 从 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。关于,谢谢

标签: javaeclipse

解决方案


这是你的问题。

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失败了。因此,您永远不会在地图中放置任何东西。更改它以检查它是否不在地图中。


推荐阅读