Practical-34
Write a Java Program which will read a text and count all occurrences of a particular word.
Introduction
This program demonstrates the usage of Java which can read a text and count all occurrences of a particular word. In other words, it allows users to search for words or string characters within a given text and count the occurrences of each result. This program prepares the students to work with strings, text files, and counting algorithms.
Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class OccurrenceCount
{
public static void main(String args[]) throws FileNotFoundException
{
int count = 0;
String search;
Scanner in = new Scanner(System.in);
System.out.print("Enter the word to be searched: ");
search = in.nextLine();
File file = new File("data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String line = sc.nextLine();
if (line.contains(search))
{
count++;
}
}
System.out.println("occurrences of the word" + search + ":" + count);
}
}
Output
Enter the word to be searched: hello
occurrences of the word hello: 2
The code takes in the word which is to be searched as an input from the user. This word is stored in the search string. Once the word is taken as an input, the .txt file is read and a line is taken in for processing at a time using the Scanner class. Next, the line taken is checked to find if it containts the word to be searched. If yes, then the counter is incremented. Finally, the occurrences of the word are printed.