2014-11-24 72 views
0

我有一个文本文件,并且想要统计我定义的特定单词的总数。从文本文件中计算特定单词 - 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的数量。 可能是什么问题?

+1

尝试回答以下问题:next()返回什么?如果你打两次会发生什么? – 2014-11-24 13:40:25

+0

@JBNizet唯一的尝试教育OP,让他自己得出结论。其他人希望快点,像秃鹰(包括我在内)。 – 2014-11-24 13:47:06

+0

@PredragMaric至少你的答案解释了什么问题,而不是只提供替代的代码,没有任何解释:) – 2014-11-24 13:50:02

回答

1

每次调用s.next()时间,它的寻找下一个字,所以每次循环正在测试一个字是“AA”或下一个字是“BB”。在循环中,您需要调用s.next(),将结果存储在变量中,然后用两个单词检查。

1

试试这个方法:

while (s.hasNext()) { 
    totalCount++; 
    String word = s.next() 
    if (word.equals(word1) || word.equals(word2)) wordCount++; 
} 
2

您在if满足调用s.next()两次,到下一个单词的每个呼叫移动。 while循环更改为

while (s.hasNext()) { 
    totalCount++; 
    String word = s.next(); 
    if (word.equals(word1) || word.equals(word2)) wordCount++; 
} 
1

您的问题是您拨打s.next()两次。每次调用都会从输入中读取一个新的令牌。

将其更改为:

while (s.hasNext()) { 
    String str = s.next(); 
    totalCount++; 
    if (str.equals(word1) || str.equals(word2)) wordCount++; 
} 
1

你在你的,如果条件调用next()两次。

尝试:

String word = s.next(); 

if (word.equals(word1) .... 
0
String[] array = new String[]{"String 1", "String 2", "String 3"}; 

    for(int i=0; i < array.length; i++) 
    { 
        System.out.println(array[i]); 
        wordCount=0; 
        while (s.hasNext()) 
        { 
         totalCount++; 
         if (s.next().equals(array[i])) 
         wordCount++; 
        } 
        System.out.println("each Word count: " + wordCount); 
    } 
3

至于对方说:问题根源,你调用next()的两倍。刚才提示如何使算法容易扩展:

Set<String> words = new HashSet<>(Arrays.asList("aa", "bb")); 
... 
while (s.hasNext()) { 
    totalCount++; 
    if (words.contains(s.next())) wordCount++; 
}