0

I'm creating quite a large, multiple class program and just need to find out if the next element in the array exists for one of my methods. (i.e. if i is the last element).

My code:

if (eMessageArray[i + 1] != null) {
    temp = stringShuffle(eMessageArray[i], eMessageArray[i + 1]);
    eMessageArray[i] = temp;
} else if (eMessageArray[i + 1] == null) {
    temp = stringShuffle(eMessageArray[i], "NULL");
    eMessageArray[i] = temp;
}
Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • 1
    And what is the problem with your code? `eMessageArray[i+1]==null` seems like right test. Also your second `if` is redundant since only case in which `else` would be executed is when `(eMessageArray[i+1]` is `null`. – Pshemo Dec 08 '15 at 17:21
  • ArrayIndexOutOfBoundsException Basically by the time the array has iterated to the end, I'm trying to access i+1 which is the same as eMessageArray.length . So I'm trying access an element that doesnt exist – Shane Monks O'Byrne Dec 08 '15 at 17:24
  • Are you running into an ArrayIndexOutOfBoundsException? If so, make sure that you're not trying to access the next element if i is the last element. – forrert Dec 08 '15 at 17:26
  • 1
    So don't test element after last one. Either limit your `i` to `array.lenbth-1` or add condition like `i+1 – Pshemo Dec 08 '15 at 17:26
  • 1
    Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) –  Dec 08 '15 at 17:29

2 Answers2

0

The problem is that when i points to the the last element of the array, then there is no element i+1, because the array is not long enough. The solution is to stop iterating with i at the second last index, so that i+1 is always a valid index. This is done with the ...length - 1 as follows:

for (int i = 0; i < eMessageArray.length - 1; i++) { // important: - 1 to omit last index for i
    if (eMessageArray[i+1]!=null){
        temp = stringShuffle(eMessageArray[i], eMessageArray[i+1]);
    } else {
        temp=stringShuffle(eMessageArray[i], "NULL");
    }
    eMessageArray[i]=temp;
}
Daniel S.
  • 6,458
  • 4
  • 35
  • 78
0

Generally when trying to access the array index out of bounds there might be some garbage values present instead, which would though not be null yet meaningless to be accessed. You would want to define the bounds of an array if you want to use it && provide that check inside your iteration for the bound range.

Naman
  • 27,789
  • 26
  • 218
  • 353