I'm writing a simple Java program that asks the user to input a string, and then counts and displays the number of times each letter in the alphabet appears in that string. When I compile, I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -25
at StringLetters.countLetters(StringLetters.java:43)
at StringLetters.main(StringLetters.java:23)
I have looked at other solutions to problems similar to mine, but none of them helped. Does anyone have any ideas? Thank you.
import java.util.Scanner;
public class StringLetters
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string of words.");
String s = scan.nextLine();
int[] counts = countLetters(s.toUpperCase());
for(int i = 0; i < counts.length; i++)
{
if (counts[i] != 0)
{
System.out.println((char)('a' + i) + " appears " + counts[i] + ((counts[i] == 1) ? "time" : " times"));
}
}
}
public static int[] countLetters(String s)
{
int[] counts = new int[26];
for (int i = 0; i < s.length(); i++)
{
if(Character.isLetter(s.charAt(i)))
{
counts[s.charAt(i) - 'a']++;
}
}
return counts;
}
}
Maprather than anint[].countLetters(s.toUpperCase());and then this:s.charAt(i) - 'a'??