Question
1. The following code segment accepts a word from the user and print the number of occurrences of each letter in the word. The program
1. The following code segment accepts a word from the user and print the number of occurrences of each letter in the word. The program will throw an exception if you enter a non-letter string. Modify the code such that it handles exception when the user enters a non-letter string.
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
//get word from user
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
//convert to all upper case
word = word.toUpperCase();
//count frequency of each letter in string
for (int i=0; i < word.length(); i++)
counts[word.charAt(i)-'A']++;
//print frequencies
System.out.println();
for (int i=0; i < counts.length; i++)
if (counts [i] != 0)
System.out.println((char)(i +'A') + ": " + counts[i]);
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started