WordCount方法

时间:2015-11-17 17:33:25

标签: java bluej word-count

我不明白为什么我的代码无效。我收到一个错误:“找不到符号 - 方法getLength(),”这是在Array类中定义的。有关如何使这种方法更好的任何建议?谢谢!

/**
     * getWordCount
     * 
     * Get a count of how many times each word occurs in an input String.
     * 
     * @param text a string containing the text you wish to analyze
     * @return a map containing entries whose keys are words, and
     *         whose values correspond to the number of times that word occurs
     *         in the input String text.
     */
    public Map<String,Integer> getWordCount(String text)
    {
         String[] parts = text.trim().split("('s|\\W)+"); 

        Map<String, Integer> wordCountMap = new TreeMap<String, Integer>();
        for(int i=0;i<parts.getLength();i++)
        {
            for(String text : parts[i].toString())
            {
                if(!wordCountMap.containsKey(text))
                {
                     wordCountMap.put(text,1);
                } else {
                    int freq = wordCountMap.get(text);
                    freq++;
                    wordCountMap.put(text,freq);
                }
                return wordCountMap;
            }
            return new TreeMap<String,Integer>();
        } 
    }

1 个答案:

答案 0 :(得分:0)

您的代码存在多个问题。

以下更改可能会有所帮助

public Map<String,Integer> getWordCount(String text)
{
    String[] parts = text.trim().split("('s|\\W)+"); 

    Map<String, Integer> wordCountMap = new TreeMap<String, Integer>();
    for (String part : parts)
    {
        if(!wordCountMap.containsKey(part))
        {
             wordCountMap.put(part,1);
        } else {
            int freq = wordCountMap.get(part);
            freq++;
            wordCountMap.put(part,freq);
        }
    }
    return wordCountMap;
}

以下测试代码的大小为5,似乎可以确认您在代码中要执行的操作。

Map<String, Integer> map = getWordCount(" the fox jumped over the moon ");
System.out.println("size:" + map.size());