我遇到了Codility问题,如果我使用A == null,仍然会遇到运行时错误

时间:2019-02-23 09:54:05

标签: java

我遇到了Codility问题,如果我使用A == null,仍然会遇到运行时错误。问题:给出了一个由N个整数组成的数组A。旋转数组意味着将每个元素右移一个索引,并将数组的最后一个元素移到第一位。

遇到错误的地方:输入([],1) 问题是null是否不能验证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;
}

因此,如果我尝试使用Try catch并成功了,则不用使用。

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;
}
} 
}

1 个答案:

答案 0 :(得分:0)

一个空数组与null不同。您还需要检查空数组。因此,您可以代替try...catch

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;
}