Java Program to Count frequency of each characters using Buffered Reader
Write a Java Program to Count frequency or occurrence of each characters using Buffered Reader.Finding characters frequency of a String means calculating the occurrence of each alphabet present in the string.
Since there’s no pre-build function present in Java for calculating the occurrence of the characters or alphabets so, we have to write a program which will give the frequency of characters present in the string.
Let’s get started :
- Firstly, the program will ask for an input string from the user.
- Then start searching for the occurrence of all the characters present inside the string to find the frequency of all the characters in the string.
- Then, Display the frequency of all the characters on the output screen as shown in the following program.
For example :
- If the user has entered – “Codezclub” .
- Then the program will give –
2. Accept a sentence from the user.
3. Extract a character.
4. Count the no. of times it occurs in the sentence.
5. Print its frequency.
6. Repeat Steps 3 to 6 till all the frequencies are printed.
Following Java Program ask to the user to enter a string to find the frequency of all the characters present in the string and display the frequency of all the characters one by one on the screen.
Below is the source code for Java Program to Count frequency or occurrence of all characters in string which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
public class Count_Frequency
public static void main(String args)throws IOException
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any string : ");
String s = br.readLine();
s=s.toLowerCase(); //converting the string into lowercase
int l=s.length(); //finding the length of the string
System.out.println("=========================="); //this is just for styling the look of the output
/* Counting frequency of alphabets begins below */
for(char i='a'; i<='z'; i++)
count = 0;
for(int j=0; j<l; j++)
ch=s.charAt(j); //extracting characters of the string one by one
if(ch==i) //first checking the whole string for 'a', then 'b' and so on
count++; //increasing count of those aplhabets which are present in the string
if(count!=0)//printing only those alphabets whose count is not '0'
Enter any string : zazaarrtewsdeddsazsa