KnowledgeBoat Logo

Computer Applications

Write a program to input a sentence. Count and display the frequency of each letter of the sentence in alphabetical order.
Sample Input: COMPUTER APPLICATIONS
Sample Output:

CharacterFrequencyCharacterFrequency
A2O2
C2P3
I1R1
L2S1
M1T2
N1U1

Java

Java String Handling

ICSE 2010

96 Likes

Answer

import java.util.Scanner;

public class KboatLetterFreq
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        String str = in.nextLine();
        str = str.toUpperCase();
        int freqMap[] = new int[26];
        int len = str.length();
        
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (Character.isLetter(ch)) {
                int chIdx = ch - 65;
                freqMap[chIdx]++;
            }
        }
        
        System.out.println("Character\tFrequency");
        for (int i = 0; i < freqMap.length; i++) {
            if (freqMap[i] > 0) {
                System.out.println((char)(i + 65) 
                            + "\t\t" + freqMap[i]);
            }
        }
    }
}

Variable Description Table

Program Explanation

Output

BlueJ output of Write a program to input a sentence. Count and display the frequency of each letter of the sentence in alphabetical order. Sample Input: COMPUTER APPLICATIONS Sample Output:

Answered By

37 Likes


Related Questions