Java ArrayIndexOutOfBounds 异常 [英] Java ArrayIndexOutOfBounds Exception
问题描述
也许我已经看这个太久了,因为我找不到问题,但它应该很简单.我在线上收到一个 ArrayIndexOutOfBounds 异常:
Perhaps I have been looking at this for too long as I cannot find the problem, yet it should be something simple. I am receiving an ArrayIndexOutOfBounds exception on the line:
nextWord = MyArray[i + 1].toLowerCase();
有人能明白为什么吗?
String currentWord = "";
String nextWord = "";
for (int i = 0; i <= MyArray.length; i++) {
// If not at the end of the array
if (MyArray.length > 0 && i < MyArray.length) {
currentWord = MyArray[i].toLowerCase();
nextWord = MyArray[i + 1].toLowerCase(); /* EXCEPTION */
System.out.println("CURRENT WORD: " + currentWord);
System.out.println("NEXT WORD: " + nextWord);
}
}
谢谢!
推荐答案
数组索引从 0
到 array.length - 1
.
数组的典型循环结构如下:
The typical loop construct for arrays is thus:
for (int i=0; i<array.length; i++) // do stuff
在你的情况下,你有一个单一的位置向前看,所以为了避免越界,你需要将该循环限制一个位置:
in your case, you've a got a single position look ahead, so to avoid out-of-bounds you need to restrict that loop by one position:
for (int i=0; i<array.length-1; i++) // do stuff
如果您将索引范围设置在循环之外,则在循环之后它将具有正确的值来分配最后一个currentWord
:
if you scope the index outside of the loop, after the loop it will have the right value to assign the last currentWord
:
int i=0;
for (; i<array.length-1; i++) // do stuff
// here i == array.length - 1, provided you don't mess with i in the "do stuff" part
这篇关于Java ArrayIndexOutOfBounds 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!