我不明白为什么我的代码不能工作。我得到一个错误:“找不到符号方法数组()”,它是在getLength类中定义的。对如何改进这种方法有什么建议吗?谢谢!
/**
* 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>();
}
}发布于 2015-11-18 02:00:37
您的代码存在多个问题。
以下更改可能会有所帮助
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());https://stackoverflow.com/questions/33763417
复制相似问题