In this program user will enter any sentence and the frequency of each words in the sentence will be displayed.
import java.io.*;
class Sentence
{
int i,j,c;
String sentence,s1,word[]=new String[20];
int x=0;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public void disp()throws Exception
{
System.out.println("Enter the sentence:");
sentence=br.readLine();
while(true)
{
i=sentence.indexOf(' ');
if(i<0)
break;
word[x++]=sentence.substring(0,i);
sentence=sentence.substring(i+1);
}
word[x++]=sentence;
for(i=0;i< x-1;i++)
{
for(j=i+1;j< x;j++)
{
if(word[i].compareTo(word[j])>0)
{
s1=word[i];
word[i]=word[j];
word[j]=s1;
}
}
}
s1=word[0];
c=1;
for(i=1;i< x;i++)
{
if(s1.equals(word[i]))
c++;
else
{
System.out.println(s1+ " frequency="+c);
c=1;
s1=word[i];
}
}
System.out.println(s1+ " frequency="+c);
}
public static void main(String args[])throws Exception
{
Sentence ob=new Sentence();
ob.disp();
}
}
Technical analysis of the program
The entered sentence is broken in to words and the words are stored in a string array. The words are then sorted which will help to count frequency of each words. Consecutive words are checked for equality and if match is found a counter is incrementd. When mismatch is found it means that the word is no more in the sentence and the word with its frequency is displayed. The mismatch word is again searched with the remaining words and the same process is repeated.Frequency of the last word is to be displayed from outside the loop as there will be no mismatch with the last word.
Sample input and output
Enter the sentence:
I live in a town which is in Burdwan
Burdwan frequence=1
I frequence=1
a frequence=1
in frequence=2
is frequence=1
live frequence=1
town frequence=1
which frequence=1
Enter the sentence:
Today is Diwali and it is being celebrated in everywhere in India
Diwali frequence=1
India frequence=1
Today frequence=1
and frequence=1
being frequence=1
celebrated frequence=1
everywhere frequence=1
in frequence=2
is frequence=2
Thanks a lot Sir for your help
ReplyDeletethanx a lot sir
ReplyDeleteThanks a lot Sir.
ReplyDeleteThanks a lot sir. Although the program is a bit lengthy, but your technical analysis regarding the program gives the jist of what all things that must be done .
ReplyDeleteWelcome.
Delete