I am new to using try catch blocks and I need some direction. I have a program that counts letters entered in a phrase from user input. The letters 'A' through 'Z' are converted to a number between 0 & 25 by subtracting the corresponding value of the Unicode character set index value of the letter that's being processed from the value of 'Z', which is 90. How would I add a try catch block inside the first for loop that translates the character to the index so that if the phrase contains any characters that are not a letter it would catch it in the ArrayIndexOutOfBoundsException. I then would have a message that prints out the non letter character in a statement to the user. I know what I want to do but, I'm having a little trouble understanding the syntax that I would need to do this. I tried to add if(counts[i] <= 64 || >= 91), but that doesn't seem to work. Do I need to convert it to a string? I know my code needs to be something like:
try {
code...
}
catch (StringIndexOutOfBoundsException exception)
{
System.out.println("Not a letter: " + counts);
}
Here is my code without the try/catch block:
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("\n Enter a single word (letters only): ");
String word = scan.nextLine();
scan.close();
//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]);
}
}