Sunday, December 18, 2011

BlueJ Program On Showing Frequency Of Characters In A Sentence


import java.io.*;
class Words2
{
  BufferedReader br;
 String text;
 char ch[];
 int len;

  public static void main(String args[])throws IOException
   {
  Words2 ob=new Words2();
 ob.accept();
 ob.result();
  }
  Words2()
  {
   br=new BufferedReader(new InputStreamReader(System.in));
  }
public void accept()throws IOException
{
 System.out.println("Enter the sentence:");
 text=br.readLine().trim();
 len=text.length();
  ch=new char[len];
 text.getChars(0,len,ch,0);


 }
public void result()
{
 int i,j;
 char ch1;
 int w;
for(i=0;i< len-1;i++)
{
 for(j=i+1;j< len;j++)
 {
    if(ch[i] >ch[j])
    {
         ch1=ch[i];
         ch[i]=ch[j];
         ch[j]=ch1;
        }
    }
}
ch1=ch[0];
System.out.println(ch1);
w=1;
for(i=1;i< len;i++)
{
 if(ch1==ch[i])
 w++;
 else
 {
     if(ch1==' ')
     System.out.println("Frequency of  space="+w);
     else
      System.out.println("Frequency of  "+ch1+" ="+w);
      w=1;
      ch1=ch[i];
    }
}
 System.out.println("Frequency of  "+ch1+" ="+w);
}
}

Technical analysis of the program on calculating frequency of letters

The sentence is first stored in a character type array so that the characters can be sorted. Next the frequency is computed using the same technique as the frequency calculation of digits in a numbers.


Sample input and output of the BlueJ program on showing frequency

Enter the sentence:
this is a test of frequency

Frequency of  space=5
Frequency of  a =1
Frequency of  c =1
Frequency of  e =3
Frequency of  f =2
Frequency of  h =1
Frequency of  i =2
Frequency of  n =1
Frequency of  o =1
Frequency of  q =1
Frequency of  r =1
Frequency of  s =3
Frequency of  t =3
Frequency of  u =1
Frequency of  y =1

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner