Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
719 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...