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?
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 calls.next(), store the result in a variable, then check that with your two words.