首页 > 解决方案 > 哈希图中的字数

问题描述

我一直在为我的计算机科学课开发一个字数统计程序,我在代码中找不到错误,但它偶尔会错误地计算字数。我已经查看了以前提出的问题,但找不到答案。谁能弄清楚我做错了什么?谢谢!

import java.util.*;

public class WordCounts extends ConsoleProgram
{
    public void run()
    {
        HashMap<String,Integer> h = new HashMap<String,Integer>();
        String input = readLine("Enter a string: ");
        String[] words = input.split(" ");
        for(int i=0; i<words.length; i++)
        {
            Integer num = h.get(words[i]);
            if( num == null)
                num = new Integer(1);

            else
                num = new Integer(num.intValue() + 1);


            h.put(words[i].toLowerCase(), num);
        }

        printSortedHashMap(h);
    }

    /*
     * This method takes a HashMap of word counts and prints out
     * each word and it's associated count in alphabetical order.
     *
     * @param wordCount The HashMap mapping words to each word's frequency count
     */
    private void printSortedHashMap(HashMap<String, Integer> wordCount){
        // Sort all the keys (words) in the HashMap
        Object[] keys = wordCount.keySet().toArray();
        Arrays.sort(keys);

        // Print out each word and it's associated count
        for (Object word : keys) {
            int val = wordCount.get(word);
            System.out.println(word + ": " + val);
        }
    }
}

标签: java

解决方案


尝试替换此行:

 Integer num = h.get(words[i]);

 Integer num = h.get(words[i].toLowerCase());

推荐阅读