简体   繁体   English

比较两个ArrayList索引时出现IndexOutOfBoundsException

[英]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. 我正在尝试编写一个程序,该程序在随机生成的20的ArrayList中找到最长的数字序列,然后在括号中标记该序列。 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. 但是,当我尝试在for循环中比较ArrayList的索引的两个值时,发生IndexOutOfBoundsException ,我不确定问题出在哪里。

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. 因为在for循环的最后一次迭代中(对于值19,您正在尝试访问dieTosses.get(i+1)处的位置20, dieTosses.get(i+1)位置不存在,因为它们的索引范围是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 根据我观察到的情况,可能是当我到达dieTosses.size()时,您正在尝试调用dieTosses.get(i + 1),这会使它超出范围,请更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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