0

I come across in Codility problem where if i used A == null a run time error still encounters. Problem: An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place.

where the error encountered: input ([],1) The question is does null doesn't validate the value of A?

class Solution {
public int[] solution(int[] A, int K) {
  if(A == null){
    return A;
  }
 for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}

So instead of using if I tried to use Try catch and it worked.

class Solution {
public int[] solution(int[] A, int K) {


try{
for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}
catch(ArrayIndexOutOfBoundsException e){
    return A;
}
} 
}
  • 2
    And just for the record: at this point in time, you should strive to **understand** errors, not to ignore them by having **meaningless** catch blocks! Print the stack trace, research the exception *meaning* and FIX your code. Please understand: every character that you put in your code DOES something. You have to invest the time to properly learn about each and any thing you put in your code. Dont go "lets ignore this for a second" ... because you dont understand the consequences of doing so! – GhostCat Feb 23 '19 at 10:02
  • 1
    And: learn about java naming conventions. Use **names** that mean something. A is a nothing telling name ... and x y ... implicitly imply "floating point numbers". Loop indexes could/should be named i, j, ... and so on. – GhostCat Feb 23 '19 at 10:03
  • No you code does not validate any value inside an empty array. Here int[] A is a reference type and as you input([],1) you will get an undefined symbol [] error. However if you write int test[] = null; input(test,1); this will compile. Here test will be having a null. Keep in mind that null is a type in java. if(A == null){ return A; } this will get executed and an empty array will be returned. – Sushrut Kanetkar Feb 23 '19 at 10:13
  • I see I get it now thanks Sushrut, also thanks GhostCat i'll remember what you've said. – benjamin palma Feb 23 '19 at 10:23

1 Answers1

0

An empty array is not the same as null. You need a check for empty array as well. So instead of try...catch, you can do:

public int[] solution(int[] A, int K) {
  if(A == null || A.length == 0) { // here!
    return A;
  }
 for(int y = 0; y < K; y++){
    int temp = A[A.length - 1];
        for(int x = A.length - 1; x > 0; x --){
            A[x] = A[x - 1];
        }
        A[0] = temp;
    }

    return A;
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313