宿命的*_*な孤独 2 java arrays for-loop boolean
假设我有一个阵列
int[] arr = {1, 2, 3, 4, 5, 6}
Run Code Online (Sandbox Code Playgroud)
我必须输入一个基于用户输入的"键"值.
如果数组有任何两个元素总和到我的键值,则返回true值或false值.为什么我的算法仍有问题?我在嵌套循环中存在一些误解吗?有什么帮助吗?
public static boolean checkPair(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == key) {
return true;
} else {
return false;
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
你的else陈词是错的.如果第一对没有相同的值,它总是返回false.
像这样更改你的代码:
public static boolean checkPair(int[] arr, int key) {
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] == key) {
return true;
}
//else {
// return false; <- this returns always false if the
// first pair isnt a i,j-match
//}
}
}
return false; // stub
}
Run Code Online (Sandbox Code Playgroud)
说明
在你的例子中 int[] arr = {1, 2, 3, 4, 5, 6}
arr[i] = 1而a[j] = 2如果设置键,任何INT除3,该方法将返回false和其他数字将不被考虑