我正在编写一个简单的Java程序,要求用户输入一个字符串,然后计算并显示字母表中每个字母出现在该字符串中的次数。编译时,出现以下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -25
at StringLetters.countLetters(StringLetters.java:43)
at StringLetters.main(StringLetters.java:23)


我研究了其他解决方案,类似于我的问题,但没有一个有帮助。有人有什么想法吗?谢谢。

    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;
    }

}

最佳答案

在传递给count方法的参数String中,您的字母不是小写英文字母,并且破坏了代码。

实际上,它们都不是小写字母,因为您正在调用s.toUpperCase(),并且似乎是要调用s.toLowerCase()。另外,您需要过滤出标点符号和所有非字母字符。您已经在这里进行操作:if (Character.isLetter(s.charAt(i)))

因此,只需将s.toUpperCase()更改为s.toLowerCase(),就可以了。

09-09 22:37
查看更多