【问题标题】:indexoutofboundsexception for loop and field循环和字段的 indexoutofboundsexception
【发布时间】:2014-11-29 09:51:35
【问题描述】:
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.)

错误信息显示:

线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:42 在 java.lang.String.charAt(未知来源) 在 CopyOfAufgabe_2.main(CopyOfAufgabe_2.java:13)``

【问题讨论】:

    标签: java eclipse string indexoutofboundsexception


    【解决方案1】:

    for (int ef = 0; ef&lt;= 25; ef++){

    应该是

    for (int ef = 0; ef&lt; 25; ef++){

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

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

    应该是

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

    具有length() 字符的字符串的字符具有从0 到length()-1 的索引。

    【讨论】:

    • 感谢您的回答。并对造成的误解深表歉意。数组应该有 26 个元素(因为英文字母有 26 个字母),我弄错了数组的设置。刚刚更正了……但是还是不行。
    • 同样的问题。
    • @Aabbccc 我已经测试了你的代码。如果你解决了上面提到的两个问题,它就会起作用。
    • @Aabbccc 你解决了第二个问题吗? (ab&lt;= text.length();)
    • @Eran 谢谢你的第二个建议。现在可以了。
    猜你喜欢
    • 2013-06-14
    • 2018-01-01
    • 2012-11-06
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    相关资源
    最近更新 更多