线程主java.lang.ArrayIndexOutOfBoundsException中的异常

时间:2013-12-03 00:39:07

标签: java arrays exception indexoutofboundsexception

我有一个错误,我正在试图找出解决方法。

这是我的代码:

private static void checkAnomalies(Name[] list){
    Name[] temp = new Name[list.length];
    int anomalyCount = 0;
    int popTwo = 0;
    int popOne = 0;
    String[] anomalies = new String[1065];

    for (int i = 0; i < list.length; i++){
        temp[i] = list[i];
    }

    for (int decade = 0; decade < 11; decade++){

        for (int index = 0; index < temp.length; index++){
            int smallestIndex = getIndexOfSmallest(decade, index, temp);
            interchange(decade, index, smallestIndex, temp);
        }

        int rank = 0;

        for (int i = 0; i < temp.length; i += 2){

            popOne = temp[i].getPop(decade);
            popTwo = temp[i+1].getPop(decade);

            if (popOne != 0){
                rank++;
            }

            if (popOne  == rank && popTwo != rank){
                String decadeYear = decadeYears(decade);
                anomalies[anomalyCount] = "One name (" + temp[i].getName() + ") for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
                anomalyCount++;
            }
            else if (popOne != rank && popTwo == rank){
                String decadeYear = decadeYears(decade);
                anomalies[anomalyCount] = "One name (" + temp[i+1].getName() + ") for " + decadeYear + ", rank " + temp[i+1].getPop(decade) + ".";
                anomalyCount++;
            }
            else if (popOne != rank && popTwo != rank){
                String decadeYear = decadeYears(decade);
                anomalies[anomalyCount] = "No names for " + decadeYear + ", rank " + temp[i].getPop(decade) + ".";
                anomalyCount++;
            }

        }
    }
}

我得到的错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4429
at NameApp.checkAnomalies(NameApp.java:495)
at NameApp.writeAnomaliesToFile(NameApp.java:260)
at NameApp.main(NameApp.java:44)

我知道list.length等于4429,我知道错误就在这一行

popTwo = temp[i+1].getPop(decade);

我怎么还能使用它,但不能超过4429.

1 个答案:

答案 0 :(得分:0)

减少循环限制以在i+1超过数组末尾之前停止迭代。

e.g。 (注意- 1

for (int i = 0; i < temp.length - 1; i += 2){