Java ArrayIndexOutOfBounds异常

时间:2010-10-28 15:44:20

标签: java arrays exception

也许我一直在看这个,因为我找不到问题,但它应该是简单的。我在行上收到了一个ArrayIndexOutOfBounds异常:

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

谢谢!

5 个答案:

答案 0 :(得分:4)

MyArray.length - 1是数组的最后一个元素。 iif的最大值MyArray.length - 1i + 1。并且您在MyArray.length中将其增加一个,因此您获得了{{1}}。当然你会收到一个例外:)

答案 1 :(得分:3)

数组索引从0array.length - 1

因此,典型的数组循环结构是:

for (int i=0; i<array.length; i++) // do stuff

在你的情况下,你有一个单一的位置向前看,所以为了避免越界,你需要将该循环限制在一个位置:

for (int i=0; i<array.length-1; i++) // do stuff

如果你将索引的范围放在循环之外,在循环之后它将具有正确的值来分配最后一个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

答案 2 :(得分:0)

因为如果我&lt; MyArray.Length,然后i + 1可以超出范围。例如,如果i = MyArray.Length - 1(上一个有效索引),那么i + 1 = MyArray.Length,这是超出界限的。

答案 3 :(得分:0)

对于数组MyArray,有效索引为[0,MyArray.length-1]。由于对于给定的i您正在访问索引为i+1的元素,因此i的有效值为[0,MyArray.length-2]

所以你可以这样做:

for (int i = 0; i <= MyArray.length-2; i++) {

    // no need of the if check anymore.
    currentWord = MyArray[i].toLowerCase();
    nextWord = MyArray[i + 1].toLowerCase(); 

答案 4 :(得分:0)

只需修复您的检查,即您不在阵列的最后一个成员。如果您位于数组的最后一个成员,则向其中添加一个将超出数组,因此您将获得该异常。你也正在跳过第一个元素,并循环遍历数组的末尾(因为你从零开始,转到长度是一个额外的循环)

for (int i = 0; i < MyArray.length; i++) {  
    currentWord = MyArray[i].toLowerCase();
    System.out.println("CURRENT WORD: " + currentWord);

    // If not at the end of the array  
    if (i != MyArray.length - 1) {  
       nextWord = MyArray[i + 1].toLowerCase();
       System.out.println("NEXT WORD: " + nextWord);
    }
}  
相关问题