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!
MyArray.length - 1
is the last element of the array. The biggest value ofi
which will go down in theif
isMyArray.length - 1
. And you increase it by one ini + 1
, so you getMyArray.length
. Of course you will receive an exception:)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)
Array indices run from
0
toarray.length - 1
.The typical loop construct for arrays is thus:
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:
if you scope the index outside of the loop, after the loop it will have the right value to assign the last
currentWord
: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.
For array
MyArray
, the valid index are[0,MyArray.length-1]
. Since for a giveni
you are accessing element at indexi+1
, valid value fori
are[0,MyArray.length-2]
.So you can do: