Java ArrayIndexOutOfBounds Exception

2020-01-29 17:44发布

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!

5条回答
Bombasti
2楼-- · 2020-01-29 17:56

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楼-- · 2020-01-29 18:09

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);
    }
}  
查看更多
手持菜刀,她持情操
4楼-- · 2020-01-29 18:19

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
查看更多
我只想做你的唯一
5楼-- · 2020-01-29 18:20

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.

查看更多
不美不萌又怎样
6楼-- · 2020-01-29 18:23

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(); 
查看更多
登录 后发表回答