我有一个文本文件,并且想要统计我定义的特定单词的总数。从文本文件中计算特定单词 - Java
我的代码:
String word1 = "aa";
String word2 = "bb";
int wordCount = 0;
//creating File instance to reference text file in Java
File text = new File("D:/project/log.txt");
//Creating Scanner instnace to read File in Java
Scanner s = new Scanner(text);
//Reading each line of file using Scanner class
while (s.hasNext()) {
totalCount++;
if (s.next().equals(word1) || s.next().equals(word2)) wordCount++;
}
System.out.println("Word count: " + wordCount);
然而,仅计算的“AA的数量。它不会计算'bb's的数量。 可能是什么问题?
尝试回答以下问题:next()返回什么?如果你打两次会发生什么? – 2014-11-24 13:40:25
@JBNizet唯一的尝试教育OP,让他自己得出结论。其他人希望快点,像秃鹰(包括我在内)。 – 2014-11-24 13:47:06
@PredragMaric至少你的答案解释了什么问题,而不是只提供替代的代码,没有任何解释:) – 2014-11-24 13:50:02