0

I have an error and I am trying to figure out how to fix it.

This is my code:

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

        }
    }
}

the error I am getting is this:

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)

I know that list.length is equal to 4429 and I know that the error is at this line here

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

how can I still use this but not go over 4429.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3044041
  • 73
  • 2
  • 8

1 Answers1

0

Decrease the limit on your loop to stop iterating before i+1 exceeds the end of the array.

e.g. (note the - 1)

for (int i = 0; i < temp.length - 1; i += 2){
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160