我的家庭作业有问题。我们的作业由在线网站评分,我不断收到关于我在下面显示的代码的以下错误。
错误:
例外情况。为 null a.java.lang.NullPointerException 引发了不正确的异常
public static int[] nearestK(int[] a, int val, int k) {
int x = 0;
if (k < x || a.length == 0 || a == null)
{
throw new IllegalArgumentException("k is not invalid");
}
if (k == 0 || k > a.length)
{
int[] incorrect = new int[0];
return incorrect ;
}
final int value = val;
Integer[] copy = new Integer[a.length];
for (int i = 0; i < a.length; i++) {
copy[i] = a[i];
}
Arrays.sort(copy,
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
int distance1 = Math.abs(value - o1);
int distance2 = Math.abs(value - o2);
return Integer.compare(distance1, distance2);
}
});
int[] answer = new int[k];
for (int i = 0; i < answer.length; i++) {
answer[i] = copy[i];
}
return answer;
}