Search code examples
javaarraysfor-loopindexoutofboundsexceptionsubtraction

Subtraction of array elements in for loop (java.lang.ArrayIndexOutOfBoundsException)


I need to subtract:

(2 - 0) and (4 - 2).

I need this to find how many numbers are missing. I'm just learning for the first time coding, and logically it seemed correct to me.

Code subtract as long as "n" is minor than "(statues[statues.length-1])" which is "4", so it should stop at "2". So I can't understand why do I get this error:

java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

Indeed, if I print "c" I can see the correct result, but obviously it keeps calculating as the error line is the "c" line.

I've changed the code to different versions and it worked, but depending on numbers in the array, something was going wrong.

public class MakeArrayConsecutive2 {

public static void main(String[] args) {
    int[] statues = {0, 2, 4};
    makeArrayConsecutive2(statues);

}

public static int makeArrayConsecutive2(int[] statues) {    
    Arrays.sort(statues);
    int count = 0;
    for (int n = statues[0]; n < statues[statues.length-1]; n++) {
            int c = statues[n + 1] - statues[n];
            System.out.println(c);
            if (c != 1) {
                count += c - 1;
            }           
    }
    System.out.println(count);
    return 0;

}

}


Solution

  • It seems like the main misconception here is about how to iterate over some structure in a for-loop. Here, you've written

    for (int n = statues[0]; n < statues[statues.length-1]; n++) {
        int c = statues[n + 1] - statues[n];
    }
    

    This is incorrect, because when you try to work with statues[statues[2]], you're effectively working with statues[4], which doesn't exist; you probably just want to reference statues[n]. The solution to this is to treat n as a regular integer which takes all values in the range [0, statues.length - 1). This would look more like

    for (int n = 0; n < statues.length - 1; n++) {
        int c = statues[n + 1] - statues[n];
    }
    

    I hope this helps, and please let me know if I was interpreting your intentions incorrectly.