我的家庭作业有问题。我们的作业由在线网站评分,我不断收到有关下面显示的代码的以下错误。
错误:
Exception conditions. Incorrect exception thrown for 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;
}
最佳答案
此行失败:
if (k < x || a.length == 0 || a == null)
因为a.length
在有机会检查a == null
之前会抛出NullPointerException。
尝试将其更改为:
if (a == null || k < x || a.length == 0)
所以首先检查空值。
关于java - 异常情况: Incorrect Exception thrown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18603798/