Written by Sai Sameera Thota on June 17, 2013 in Java > Programming

Java Program to Count Frequency of Words in given Text

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Question:
Write a Java program to make frequency count of words in a given text.

Solution:
The program takes a text and a word as input and displays the frequency of the word in the given text.
This program uses the concept of string tokenizer to find the frequency of the word. Each token in the
text is compared with the given word and if the token matches with the given word, the count variable is
incremented.

import java.io.*;
import java.util.*;
public class FrequencyOfWords
{

	public static void main(String[] args)throws IOException
	{
		System.out.print("\nEnter Some Text:");

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String text = br.readLine();
		String ans = "";
		do
		{

			System.out.print("\nEnter A Word You Want To Verify The Frequency:");
			String word = br.readLine();

			int count = 0;

			StringTokenizer st = new StringTokenizer(text);

			while (st.hasMoreTokens())
			{
				if (st.nextToken().equals(word))
				{
					count++;
				}
			}

			System.out.println("\nFrequency of \"" + word + "\" is " + count + " times");
			System.out.print("\nDo You Want Verify The Frequency Of One More Word[Y/N]:");

			ans = br.readLine();
		} while (ans.equals("Y") || ans.equals("y"));
	}
}

Output:
java program to make frequency count of words in a given text

{ 2 comments… read them below or add one }

Someguy March 16, 2014 at 10:58 pm

what if i want it to do letters?

Reply

Sai Sandeep Thota March 18, 2014 at 10:08 am

Leave a Comment

Previous post:

Next post: