Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...