Program to accept a sentence which is terminated by ‘.’ or ‘?’ or ‘!’ only and print word frequency without repetition.
Example:
“Learning to code is to create.”. The program should generate the following output.
| Word | Frequency |
| Learning | 1 |
| to | 2 |
| code | 1 |
| is | 1 |
| create | 1 |
Note: There is no repetition in the word while printing its frequency.
Java
import java.util.*;
public class WordFrequency
{
public static void main(String args[])
{
String str="",wrd="";
int l=0,count=0,f=0;
char ch=' ';
Scanner sc=new Scanner(System.in);
System.out.println("Enter a sentence ending with '.' or '?' or '!'");
str=sc.nextLine();
str=str.trim();
l=str.length();
ch=str.charAt(l-1);
if(!(ch=='.'||ch=='?'||ch=='!'))
{
System.out.println("Error! Sentence must be terminated by punctuation");
System.exit(1);
}
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch=='!')
{
count++;
}
}
String w[]=new String[count];
count=0;
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch==' '||ch=='.'||ch=='?'||ch=='!')
{
w[count]=wrd;
wrd="";
count++;
}
else
{
wrd=wrd+ch;
}
}
System.out.println("Word\t\t\tFrequency");
for(int i=0;i<count;i++)
{
wrd=w[i];
for(int j=0;j<count;j++)
{
if(wrd.compareTo(w[j])==0&&w[j]!="")
{
f++;
w[j]="";
}
}
if(f>0)
{
System.out.println(wrd+"\t\t\t"+f);
}
f=0;
}
}
}Java