In: Computer Science
Write a program that will read a line of text. Display all the letters that occure in the text, one per line and in alphabetical order, along with the number of times each letter occurs in the text. Use an 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 b’s, and so forth, Alloow both upperCase and lower Case. Define a method that takes a character as an argument and returns an int value that is the correct index for that character. For example, the argument ‘a’ results in 0 as the return value, the argument ‘b’ gives 1 as the return value, and so on. Allow the user to repaet this task until the user says she/he is through.
JAVA
Please find your solution below and if any doubt do comment and do upvote.
import java.util.*;
public class Main
{
//return the index for respective Character
public static int getIndex(char ch){
return (int)(ch-'a');
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(true){
//array to store the frequence
int []charFrequency=new int[26];
//take a line of text from user
String str=sc.nextLine();
//convert it to lower case since
//upper and lower are to be treated same
//for this program
str=str.toLowerCase();
//condition to break out from the loop
if(str.equals("she is through")||str.equals("he is through")){
break;
}
for(int i=0;i<str.length();i++){
//determines if it alphabet or not
if(Character.isLetter(str.charAt(i))){
charFrequency[getIndex(str.charAt(i))]+=1;
}
}
//display the frequence of Character
for(int i=0;i<26;i++){
if(charFrequency[i]==0){
continue;
}
else{
System.out.println("The letter "+(char)(i+'A')+" occured "+charFrequency[i]+" times in the text");
}
}
}
}
}