Friday, August 17, 2012

BlueJ Program To Find The Character Which Occurred Maximum Times In A String


Write a program in java to input a sentence from the user and print the letter which has been used the most number of times in that sentence.

 import java.io.*;
 class Strr
{
String str;
char ch;
char ch1[];
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
void take() throws Exception
{
System.out.println("Enter the sentence: ");
str=br.readLine();
ch1=new char[str.length()];
str.getChars(0,str.length()-1,ch1,0);
for(i=0;i< ch1.length-1;i++)
{
 for(j=i+1;j< ch1.length;j++)
 {
   if(ch1[i]>ch1[j])
   {
    ch=ch1[i];
    ch1[i]=ch1[j];
    ch1[j]=ch;
    }
    }
    }
    j=1;
    ch=ch1[0];
    for(i=1;i< ch1.length;i++)
    {
     if(ch==ch1[i])
     j++;
     else
     {
      ch=ch1[i];
      j=1;
      }
      }
      System.out.println(ch+ " occured maximum times in '"+str+ "' -"+ j+" times");
      }
 public static void main(String args[])throws Exception
{
Strr obj=new Strr ();
obj.take();
}
}
Few words about the function getChars():

getChars () function of String class takes 4 values as arguments. The first value indicates from which index of the invoking string the characters will be strored in the char array. The second argument specifies the last index of the character to be retrieved from the invoking string. The third argument is the char type array and 4rth argument is the location of the char type array from where the characters will be stored.

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner