need help printing single error
Here's my code. I need to figure out how to print the specific character in the string (say I input word5 - the the erroneous character would be the 5) that keeps the code from working.
<code>
// ************************************************** **************
// CountLetters.java
//
// Reads a words from the standard input and prints the number of
// occurrences of each letter in that word.
//
// ************************************************** **************
import java.util.Scanner;
public class CountLetters
{
public static void main(String[] args)
{
int[] counts = new int[26];
Scanner scan = new Scanner(System.in);
// Read word from user
System.out.print("Enter a single word (letters only, please): ");
String word = scan.nextLine();
// Convert input to all upper case
word = word.toUpperCase();
// Count frequency of each letter in string
try {
for (int index=0; index < word.length(); index++)
counts[word.charAt(index)-'A']++;
// Print frequencies of letters
System.out.println();
for (int index=0; index < counts.length; index++)
if (counts [index] != 0)
System.out.println((char)( index +'A') + ": " + counts[index]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.err.println( word +" is not just letters, dude.");
}
}
}
</code>
Re: need help printing single error
you again, without code tags again.....
Re: need help printing single error
After converting to upper case, you use this statement to increment one of the 26 counters corresponding to characters 'A' - 'Z' right?
Code java:
counts[word.charAt(index)-'A']++;
If the current character is not in the range 'A' through 'Z', the index value will be out of bounds (less than zero or greater than 25). So, you have a way and a place to identify the Bad Guy right there so that you can not only report the specific problem, but you can prevent the "index out of bounds" exception from happening. (Test the character before trying to use it in the increment statement.)
Cheers!
Z