我有一个方法,它将单个单词作为String返回。我需要计算读取文本块的方法返回的所有单词。问题是我正在计数,但输出错误。它在重复。不太确定出了什么问题?
private int totalWords = 0;
private static Map<String, Integer> wordFrequency = new HashMap<String, Integer>();
public static void findResult(CharacterReader characterReader)
{
boolean x = true;
CharBuffer buffer = CharBuffer.allocate(100);
String str = "";
try
{
while(x)
{
char cha = characterReader.getNextChar();
Set<Character> charSet = new HashSet<Character>();
charSet.add(',');
charSet.add('.');
charSet.add(';');
charSet.add(':');
charSet.add('\'');
charSet.add('~');
charSet.add('?');
charSet.add('!');
charSet.add('%');
while(cha != ' ' && !charSet.contains(cha))
{
buffer.put(cha);
cha = characterReader.getNextChar();
}
buffer.flip();
str = buffer.toString();
buffer.clear();
countWords(str);
System.out.println(wordFrequency);
}
}catch(EOFException e)
{
x = false;
}
private static void countWords(String word)
{
if (wordFrequency.containsKey(word))
{
Integer count = wordFrequency.get(word);
count++;
wordFrequency.put(word, count);
} else {
wordFrequency.put(word, 1);
}
}
public static void main (String args[])
{
CharacterReader cr = new SimpleCharacterReader();
findResult(cr);
}
答案 0 :(得分:1)
移动
的System.out.println(wordFrequency);
在try语句之外。您正在每个单词后打印整个集。
答案 1 :(得分:0)
这就是你放置System.out.println的地方。你已经在循环中 了!
while(x) {
// .....
countWords(str);
System.out.println(wordFrequency);
}
解决方案:在循环之后执行此操作。
while(x) {
// .....
countWords(str);
}
System.out.println(wordFrequency);
答案 2 :(得分:0)
尝试移动 的System.out.println(wordFrequency); out while while循环括号...