7

これが私のコードです:

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

このプログラムの目的は、ユーザーに文字列を要求し、文字列内で各文字が使用されている回数をカウントすることです。

プログラムをコンパイルすると、正常に動作します。プログラムを実行すると、ポップアップ ボックスに文字列を入力できますが、文字列を送信して [OK] を押すと、次のようなエラーが表示されます。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)

問題が何であるか、またはそれを修正する方法が完全にはわかりません。

4

4 に答える 4

18
for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

このセミコロンを使用すると、ループは までループしi == total.length、何もせずに、ループの本体であると考えていたものが実行されます。

于 2013-08-31T15:52:01.337 に答える
9
for ( i = 0; i < total.length; i++ ); // remove this
{
    if (total[i]!=0)
        System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}

for ループはi=26(26 はtotal.length) までループし、次に yourifが実行され、配列の境界を超えます。ループ;の最後にある を削除します。for

于 2013-08-31T15:52:09.647 に答える