简体   繁体   English

数组索引超出范围错误

[英]Array Index Out Of Bounds error

Okay so I am getting an error for my code that is trying to count how many of each integer there are in the array. 好的,我的代码出现错误,试图计算数组中每个整数的数量。 And so im not sure how to fix it. 因此,我不确定如何解决它。 Im getting the error on the while loop at the bottom. 我在底部的while循环中收到错误。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

            if (ndx != array.length)
                while (array[ndx] == array[ndx + 1])
                    ndx++;

On the last iteration of the outer for loop, ndx is one less than array.length, so when you call array[ndx+1], that is equivalent to array[array.length], which out of bounds, since arrays start indexing at 0. Changing your bottom if statement to: 在外部for循环的最后一次迭代中,ndx比array.length小一个,因此,当您调用array [ndx + 1]时,它等效于array [array.length],由于数组开始索引,因此超出了范围在0。将您的底部if语句更改为:

if (ndx != array.length-1)

should do the trick. 应该可以。

It's also incrementing ndx in the final while loop, so there should be a conditional to check for that, too: 它也在最后的while循环中增加ndx,因此也应该有条件检查:

while(ndx != array.length-1 && array[ndx]==array[ndx+1]) 

Since you take care of the array.length-1 condition in the while now, you can get rid of the if that had it in the above line. 由于您现在已经处理了array.length-1条件,因此可以摆脱上面一行中的if。 Hope that helps! 希望有帮助!

You get the exception because of this line of code: 由于此行代码,您将获得异常:

while (array[ndx] == array[ndx + 1])

On the last iteration of the loop, ndx is equal to array.length - 1 在循环的最后一次迭代中,ndx等于array.length - 1

When you try to access array[ndx + 1] you are attempting to access an array index that is out of range. 当您尝试访问array[ndx + 1]您正在尝试访问超出范围的数组索引。

You should change the if statement above the while loop to this: 您应该将while循环上方的if语句更改为此:

if (ndx != array.length - 1)

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

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