Java ArrayIndexOutOfBounds Exception

2020-01-29 17:39发布

问题:

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

Can anyone see why?

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

Thanks!

回答1:

Array indices run from 0 to 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

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


回答2:

MyArray.length - 1 is the last element of the array. The biggest value of i which will go down in the if is MyArray.length - 1. And you increase it by one in i + 1, so you get MyArray.length. Of course you will receive an exception:)



回答3:

Because if i < MyArray.Length, then i+1 CAN be out of bounds. For example, if i = MyArray.Length - 1 (Last valid index), then i + 1 = MyArray.Length, which is out of bounds.



回答4:

For array MyArray, the valid index are [0,MyArray.length-1]. Since for a given i you are accessing element at index i+1, valid value for i are [0,MyArray.length-2].

So you can do:

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


回答5:

Simply fix your check that you are not at the last member of the array. If you are at the last member of the array, adding one to it will go beyond the array and thus you will get that exception. Also you are skipping the first element, and looping past the end of the array (since you start at zero, going to the length is one extra loop)

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