-1
for(int i = q.length-1; i >= 0; i--){
        if(q[i] != i+1){
            try{
                if(((i-1)>=0) & (q[i-1] == (i+1))){

                    steps++;
                    q[i-1] = q[i];

                    q[i] = i+1;
                    System.out.println("here "+i);
                }
                if(((i-2) >=0) & (q[i-2] == (i+1))){

                    q[i-2] = q[i-1];
                    q[i-1] = q[i];
                    q[i] = i+1;
                    steps += 2;
                }else{
                    System.out.println("Too chaotic");
                    return;
                }
            }catch(Exception e){
                System.out.println("error at the " +i + " exception" +e);
            }
        }
    }
    System.out.println(steps);

* The last value of i, I get in the catch is 1. I tried to print i in the if condition and it is printing the i value as 1 till the last line. Now, I don't understand where the exception is happening? *

1 Answers1

0

Inside the second nested-if statement, you try to access q[i-2]. But you try to do so only after checking if i - 2 >= 0, right? Wrong! You have used the bitwise AND (&) instead of a logical AND (&&).

if(((i-2) >=0) & (q[i-2] == (i+1)))

If it were a logical AND, the next condition inside the statement will not be checked if i - 2 was less than 0, thus preventing the access to q[i - 2]. Since it is a bitwise AND, both the operands will be evaluated and the evaluation of q[i - 2] at i = 1 causes the Array Index Out Of Bound exception.

That is why, the last value of i you get in the catch is 1.

This is a sufficient reason to throw the exception, but the same problem stays with the first nested-if statement. It could have been caused by this if you were traversing the array in the other direction or if there was no problem at i = 1. Therefore, in order to prevent this error, you should change both of those & into &&.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53