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

Categories

0 votes
758 views
in Technique[技术] by (71.8m points)

arrays - Java ArrayIndexOutOfBounds Exception

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...