In this assignment you will write a program that counts their frequency with whi
ID: 3866772 • Letter: I
Question
In this assignment you will write a program that counts their frequency with which letters appear in a string of text. Character frequency is useful in deciphering simple encryption schemes (for example, as in The Gold Bug by Edgar Allen Poe). Prompt the user for an input string, then count the number of times each letter appears in the string, treating upper and lowercase letters the same. Non-letters are ignored. It may be useful to know that if myChar is a variable containing a uppercase letter, myChar - 'A' will yield the position of that letter within the alphabet. For example, 'C' - 'A' is 2, while 'Z' - 'A' is 25. Of course, 'A' - 'A' is 0. An efficient solution to this problem will need to use an array to hold the frequency count for each letter.
Sample run:
Please enter a string: Hello world! Happy day!
A 2
B 0
C 0
D 2
E 1
F 0
G 0
H 2
I 0
J 0
K 0
L 3
M 0
N 0
O 2
P 2
Q 0
R 1
S 0
T 0
U 0
V 0
W 1
X 0
Y 2
Explanation / Answer
import java.util.*;
public class MyClass{
public static void main(String []args){
Scanner s = new Scanner(System.in);
System.out.println("Please enter a string");
String string = s.nextLine();
int length = string.length();
Map<Character, Integer> count = new HashMap<Character, Integer>(Math.min(length, 26));
for (int j = 0; j < length; ++j)
{
char charAt = string.charAt(j);
if (!count.containsKey(charAt))
{
count.put(charAt, 1);
}
else
{
count.put(charAt, count.get(charAt) + 1);
}
}
for(Character key : count.keySet())
{
System.out.println(key + " " + count.get(key));
}
}
}