【问题标题】:Exception in thread main java.lang.ArrayIndexOutOfBoundsException [duplicate]线程主java.lang.ArrayIndexOutOfBoundsException中的异常[重复]
【发布时间】:2013-12-18 21:25:52
【问题描述】:

我有一个错误,我正在想办法解决它。

这是我的代码:

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。

【问题讨论】:

  • 将停止循环的条件改为少两个:for (int i = 0; i &lt; temp.length - 2; i += 2){。你应该能够弄清楚这一点。
  • 啊有道理哈哈谢谢梅恩
  • 如果没有提供所有相关方法,我无法运行您的代码,但我认为这是因为您在for 循环中执行i += 2

标签: java arrays exception indexoutofboundsexception


【解决方案1】:

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

例如(注意- 1

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

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    • 1970-01-01
    • 2011-07-07
    • 2016-01-27
    相关资源
    最近更新 更多