数组索引超出范围异常(Java)

Box*_*ras 6 java arrays runtime-error

这是我的代码:

public class countChar {

    public static void main(String[] args) {
        int i;
        String userInput = new String();

        userInput = Input.getString("Please enter a sentence");

        int[] total = totalChars(userInput.toLowerCase());

        for (i = 0; i < total.length; i++);
        {
            if (total[i] != 0) {
                System.out.println("Letter" + (char) ('a' + i) + " count =" + total[i]);
            }
        }
    }

    public static int[] totalChars(String userInput) {
        int[] total = new int[26];
        int i;
        for (i = 0; i < userInput.length(); i++) {
            if (Character.isLetter(userInput.charAt(i))) {
                total[userInput.charAt(i) - 'a']++;
            }
        }
        return total;
    }
}
Run Code Online (Sandbox Code Playgroud)

程序的目的是向用户询问字符串,然后计算字符串中每个字符的使用次数.

当我去编译程序时,它工作正常.当我运行程序时,我能够在弹出框中输入一个字符串,但在我提交字符串并按OK后,我收到错误,说

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)
Run Code Online (Sandbox Code Playgroud)

我不完全确定问题是什么或如何解决它.

JB *_*zet 17

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here
Run Code Online (Sandbox Code Playgroud)

使用这个分号,循环循环直到i == total.length,什么都不做,然后你想到的是循环的主体被执行.


Sot*_*lis 7

for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}
Run Code Online (Sandbox Code Playgroud)

for循环循环直到i=26(其中26为total.length)然后if执行,遍历数组的边界.删除循环;结束时的for.