Question:
How to count the number times a certain word appears in a file?
Answer:
Use the method Scanner.next() to read in each word of the file and then compare it with the desired word.
Code:
import java.io.*; import java.util.*; public class CountWords { public static void main(String[] args) { int count=0; String word = "cat"; try { File file = new File("file.txt"); Scanner sc = new Scanner(new FileInputStream(file)); while(sc.hasNext()){ if(word.equalsIgnoreCase(sc.next())){ count = count + 1; } } } catch (Exception e) { } System.out.println("Number of " + word + " words: " + count); } }
Output:
$ cat file.txt Dog cat dog cat Cat dog cat dog $ java CountWords Number of cat words: 4