indexoutofboundsexception for loop and field


public class Task { 
    public static void main(String[] args) {
        String text ="a subject is the noun that is doing the main verb."; 
        int[] field = new int[26];
        int xy = 0; //xy will be the total number of the letter in the sentence

        char cd = 'a';
        for (int ef = 0; ef<= 25; ef++){
            for (int ab = 1; ab<= text.length(); ab++){
                    if (cd == text.charAt(ab)){ // Eclipse says that this line has problem (at CopyOfAufgabe_2.main(CopyOfAufgabe_2.java:13)
                        field[ef]=field[ef]+1;
                        xy++;
                    }
                }
            cd++;
            }
    }
}
'

'此任务有两个目的:

1. find the total number of letters in the sentence
2. find the number of respective letter (i.e. how many "a"s, how many "b"s, etc. The numbers are assigned to the field created in the fifth line (one number for each object)) (It is assumed that every letter in the sentence is not capitalized.)

显示错误消息:

线程"main"中的异常 java.lang.StringIndexOutOfBounds异常:字符串索引超出范围:42 at java.lang.String.charAt(未知来源( at CopyOfAufgabe_2.main(CopyOfAufgabe_2.java:13(''

for (int ef = 0; ef<= 25; ef++){

应该是

for (int ef = 0; ef< 25; ef++){

一个包含 25 个元素的数组具有从 0 到 24 的索引。

for (int ab = 1; ab<= text.length(); ab++){

应该是

for (int ab = 0; ab< text.length(); ab++){

包含 length() 个字符的字符串的索引从 0 到 length()-1

最新更新