gpt4 book ai didi

java - 异常情况: Incorrect Exception thrown

转载 作者:行者123 更新时间:2023-12-02 06:46:23 24 4
gpt4 key购买 nike

我的家庭作业有问题。我们的作业由在线网站评分,我不断收到有关下面显示的代码的以下错误。

错误:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com