javaarraysfor-loopjava.util.scannerarrayindexoutofboundsexception

Why the count is not printing after for loop?


After each loop count and count1 are updated. After giving inputs in Scanner, I'm not getting any output.

Scanner sc = new Scanner(System.in);
int t = sc.nextInt(); // t=1
while (t != 0) {
    int n = sc.nextInt(); // n=5
    int a[] = new int[n]; // a = { 1,2,5,6,7 }

    for (int i = 0; i < n; i++) {
        a[i] = sc.nextInt();
    }
    int count = 0, count1 = 0;
    for (int i = 0; i < n; i++) {
        if ((a[i + 1] - a[i]) > 2) {
            count++;
        } else {
            count1++;
        }
    }
    // this doesn't get printed
    System.out.println(count + 1 + " " + count1);

    t--;
}

Solution

  • The conditions in the following code block will result in an ArrayIndexOutOfBoundsException as when i = n - 1, if ((a[i + 1] - a[i]) > 2) will try to get an element from a[n - 1 + 1] i.e a[n] which you already know is invalid because the indices in a[] are in the range 0 to n - 1:

    for (int i = 0; i < n; i++) {
        if ((a[i + 1] - a[i]) > 2)
    

    You can put it like

    for (int i = 0; i < n -1 ; i++) {
        if ((a[i + 1] - a[i]) > 2)
    

    After this correction, given below is the result of a sample run:

    1
    5
    1 2 5 6 7
    2 3
    

    It is because count1++ gets executed for 1 2,, 5 6 and 6 7 while count++ gets executed only for 2 5.