简体   繁体   中英

IndexOutOfBoundsException while comparing two ArrayList indexes

I'm trying to write a program that finds the longest sequence of numbers in a randomly generated ArrayList of 20 and then marks that sequence in parentheses. However, when I try to compare two values of the indexes of the ArrayList in a for loop, and IndexOutOfBoundsException occurs and I'm not sure where the problem is.

ArrayList<Integer> dieTosses = new ArrayList<Integer>();
for(int i = 0; i < 20; i++)
    {  
        dieTosses.add((int) (Math.random()*6)+1);
    }
    int longestRun = 1;
    int runTracker = 1;
    for(int i = 0; i < dieTosses.size(); i++) //The problem occurs here
    {
        if(dieTosses.get(i) == dieTosses.get(i+1))
        {                                                                        
            longestRun++;
        }
        else if(longestRun > runTracker);
        longestRun = runTracker;
    }
    System.out.println(dieTosses);
    System.out.println(longestRun); 

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 20, Size: 20
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at DieTossing.DieTosser.main(DieTosser.java:18)

You have problem at

if(dieTosses.get(i) == dieTosses.get(i+1)) 

because at the last iteration of the for loop (for value 19 you are trying to access location 20 at dieTosses.get(i+1) .which is not present because they are indexed through 0-19.

So try this.

 for(int i = 1; i < dieTosses.size(); i++) 
    {
        if(dieTosses.get(i-1) == dieTosses.get(i))
        {                                                                        
            longestRun++;
        }
        else if(longestRun > runTracker);
        longestRun = runTracker;
    }

OR

 for(int i = 0; i < dieTosses.size()-1; i++) 
    {
        if(dieTosses.get(i) == dieTosses.get(i+1))
        {                                                                        
            longestRun++;
        }
        else if(longestRun > runTracker);
        longestRun = runTracker;
    }

which ever version you like

Based on what I observed, it could be when i reaches dieTosses.size(), you are trying to call dieTosses.get(i+1) which cause it to be out of bound, change your

for(int i = 0; i < dieTosses.size(); i++)

to

for(int i = 0; i < dieTosses.size()-1; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM