Write a program to input a string in uppercase and print the frequency of each character.

Java Programming Language (Article) (Program)

43

Write a program to input a string in uppercase and print the frequency of each character.

Example:

Input: COMPUTER HARDWARE

Output:

CHARACTERS   FREQUENCY
A            2
C            1
D            1
E            2
H            1
M            1
O            2
P            1
R            2
T            1
U            1
W            1

Program:

import java.io.*;

class Frequency {
    String s;
    int i, j, l, f;

    void display() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a string in upper case:");
        s = br.readLine();
        l = s.length();

        System.out.println("CHARACTERS   FREQUENCY");
        for (i = 65; i <= 90; i++) { // ASCII values for 'A' to 'Z'
            f = 0;
            for (j = 0; j < l; j++) {
                if (s.charAt(j) == i) {
                    f++;
                }
            }
            if (f > 0) {
                System.out.println((char)i + "\t\t" + f);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        Frequency freq = new Frequency();
        freq.display();
    }
}

Output:


                                        

Explanation:

Variable Table

Variable Type Description
s String To store the input string.
i int Loop variable for ASCII values from 65 ('A') to 90 ('Z').
j int Loop variable for iterating through the string.
l int To store the length of the input string.
f int To store the frequency of each character.

This program counts and prints the frequency of each character in the input string, considering only uppercase letters.


This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.