write a program that will read a line of text that ends with a period, which ser
ID: 3558896 • Letter: W
Question
write a program that will read a line of text that ends with a period, which serves as sentinel value. display all the letters that occur in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text. use the array of base type int of length 26, so that the element at index 0 contains the number of a's, the element at index 1 contains the number of bs and so fourth. allow both upper and lower case letters as input but treat uppercase and lowercase versions of the same letter as being equal
Explanation / Answer
import java.util.Scanner;
public class CountChar {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
String sent = "";
while (true) {
System.out.println("Please enter sentence (or empty to exit)");
sent = cin.nextLine();
if ("".equals(sent))
break;
process(sent);
}
}
private static void process(String sent) {
int[] arr = new int[26];
sent = sent.toLowerCase();
System.out.println(sent);
for (int i = 0; i < sent.length(); ++i)
if (sent.charAt(i) >= 'a' && sent.charAt(i) <= 'z')
++arr[sent.charAt(i) - 'a'];
for (int i = 0; i < 26; ++i)
System.out.println((char)('a' + i) + ": " + arr[i]);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.