Write a program that reads a string from the keyboard and computes the two array
ID: 3912031 • Letter: W
Question
Write a program that reads a string from the keyboard and computes the two arrays of integers upperCase, and lowerCase, each of size 26. The first one represents the frequency of upper case letters and the second one represents the frequency of lower case letters in the input string. After computing these arrays, the program prints the frequencies in the following format: The frequency of the letter A- The frequency of the letter B- Asume the input string contains only upprcase and lower case letters. Your solution should be efficient and it does not use a sequence of 26 IF statements or a Switch statement You may need the casting operation to convert int to char and vice versa.Explanation / Answer
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// TAKING User input
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String text = sc.next();
// declaring 2 arrays
int[] upper = new int[26];
int[] lower = new int[26];
// looping through each letter and incrementing it's count accordingly
for(int i=0; i<text.length(); i++)
{
if(text.charAt(i) >= 'a' && text.charAt(i) <= 'z')
{
lower[(int)text.charAt(i)-97]++;
}
else if(text.charAt(i) >= 'A' && text.charAt(i) <= 'Z')
{
upper[(int)text.charAt(i)-65]++;
}
}
for(int i=0; i<26; i++)
{
System.out.printf("%c = %d ", 97+i, lower[i]);
}
for(int i=0; i<26; i++)
{
System.out.printf("%c = %d ", 65+i, upper[i]);
}
}
}
/*SAMPLE OUTPUT
Enter a string: CheggIndiaWorks
a = 1
b = 0
c = 0
d = 1
e = 1
f = 0
g = 2
h = 1
i = 1
j = 0
k = 1
l = 0
m = 0
n = 1
o = 1
p = 0
q = 0
r = 1
s = 1
t = 0
u = 0
v = 0
w = 0
x = 0
y = 0
z = 0
A = 0
B = 0
C = 1
D = 0
E = 0
F = 0
G = 0
H = 0
I = 1
J = 0
K = 0
L = 0
M = 0
N = 0
O = 0
P = 0
Q = 0
R = 0
S = 0
T = 0
U = 0
V = 0
W = 1
X = 0
Y = 0
Z = 0
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.