import java.util.*;
class Main
{
String str1,str[],str2[];
int arr[];
int i,j,len,c,k,x;
String temp;
StringTokenizer stk;
Scanner sc=new Scanner(System.in);
void show()
{
i=0;
k=0;
System.out.print("\nEnter Number of Sentences:");
c=sc.nextInt();
if(c<1||c>4)
{
System.out.print("\nInvalid Entry");
System.exit(0);
}
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.print("Enter the sentences:");
str1=sc.nextLine().trim();
len=str1.length();
if(str1.charAt(len-1)=='.'||str1.charAt(len-1)==','||str1.charAt(len-1)=='?'||str1.charAt(len-1)=='!')
break;
else
System.out.print("\nTerminate the sentence with specified characters:");
}
stk=new StringTokenizer(str1,".,?! ");
c=stk.countTokens();
str=new String[c];
str2=new String[c];
arr=new int[c];
for(i=0;i<c;i++)
arr[i]=-1;
i=0;
while(stk.hasMoreTokens())
{
str[i++]=stk.nextToken();
}
for(i=0;i<c-1;i++)
{
for(j=i+1;j<c;j++)
if(str[i].compareTo(str[j])>0)
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
str1=str[0];
k=1;
for(i=1;i<c;i++)
{
if(str[i].equals(str1))
k++;
else
{
str2[x]=str1;
arr[x++]=k;
k=1;
str1=str[i];
}
}
str2[x]=str1;
arr[x++]=k;
for(i=0;i<x;i++)
{
for(j=i+1;j<x;j++)
{
if(arr[i]>arr[j])
{
int t=arr[i];
arr[i]=arr[j];
arr[j]=t;
temp=str2[i];
str2[i]=str2[j];
str2[j]=temp;
}
}
}
System.out.println("\nWord Frequency");
for(i=0;i<x;i++)
System.out.println(str2[i]+" "+arr[i]);
}
public static void main(String[] args)
{
new Main().show();
}
}
Sample Input & Output
Enter Number of Sentences:3
Enter the sentences:this is a test. this is another, where are others?
Word Frequency
a 1
another 1
are 1
others 1
test 1
where 1
this 2
is 2
No comments:
Post a Comment