gpt4 book ai didi

java - 虽然循环保证返回一个值,但应该用什么替换 return 语句?

转载 作者:行者123 更新时间:2023-12-02 12:48:34 25 4
gpt4 key购买 nike

以下代码应返回排序数组中最接近输入数字“x”的值。 while 循环保证返回。但编译器强制我返回一个值是可以理解的。我的问题是关于所涉及的最佳实践。在编译器强制返回语句的情况下,使用的一般约定是什么?即抛出异常?返回默认值? ETC ?

注意:我选择了“IllegalArgumentException”
http://codereview.stackexchange.com/questions/47328/find-the-value-nearest-to-k-in-the-sorted-array。我没有任何答案可供选择,但感谢大家的见解。我不知道这种情况下的 SO 协议(protocol)

/**
* Given a sorted array returns the 'closest' element to the input 'x'.
* 'closest' is defined as Math.min(Math.abs(x), Math.abs(y))
*
* Expects a sorted array, and if array is not sorted then results are unpredictable.
*
* @param a The sorted array a
* @return The nearest element
*/
public static int getClosestK(int[] a, int x) {

int low = 0;
int high = a.length - 1;

while (low <= high) {
int mid = (low + high) / 2;

// test lower case
if (mid == 0) {
if (a.length == 1) {
return a[0];
}

return Math.min(Math.abs(a[0] - x), Math.abs(a[1] - x)) + x;
}


// test upper case
if (mid == a.length - 1) {
return a[a.length - 1];
}

// test equality
if (a[mid] == x || a[mid + 1] == x) {
return x;
}


// test perfect range.
if (a[mid] < x && a[mid + 1] > x) {
return Math.min(Math.abs(a[mid] - x), Math.abs(a[mid + 1] - x)) + x;
}

// keep searching.
if (a[mid] < x) {
low = mid + 1;
} else {
high = mid;
}
}

// return a[0]; ?????
}

最佳答案

如果您知道仍然会返回一个值,但编译器无法确定它,这是一个程序员错误,因此您可以允许自己::

throw new IllegalStateException();

而不是返回一个无论如何都会出错的值。

关于java - 虽然循环保证返回一个值,但应该用什么替换 return 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23101700/

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