Count specific words from text file - Java

6.8k Views Asked by At

I have a text file and I want to count the total number of specific words I have defined.

My code:

    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);

However, it only counts the number of 'aa's. It doesn't count the number of 'bb's. what could be the problem?

7

There are 7 best solutions below

0
James Westman On BEST ANSWER

Each time you call s.next(), it's finding the next word, so each loop is testing whether one word is "aa" or the next word is "bb". Within the loop, you would need to call s.next(), store the result in a variable, then check that with your two words.

0
Tobi On

Try this way:

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

You are calling s.next() twice in if condition, and each call moves on to the next word. Change your while loop to

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

Your problem is the you are calling s.next() twice. Each call reads a new token from the input.

Change it to :

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

You call next() two times in your if-condition.

try:

String word = s.next();

if ( word.equals(word1) ....
0
AudioBubble On
    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);
     }
0
DontRelaX On

As other said: root of problem that you call next() twice. There just hint how to make your algo easy to extend:

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