我在 java 中编写了下面的代码来比较并返回数组中的 searhKey,但没有返回数组中的任何内容
package arraytest;
public class ArrayTest {
public static void main(String[] args) {
int objType[] = new int[10];
int i = 0;
int arrSize;
int searchKey = 0;
objType[0] = 20;
objType[1] = 15;
objType[2] = 10;
objType[3] = 11;
objType[4] = 17;
arrSize = 5;
for (i = 0; i < arrSize; i++) {
System.out.println(objType[i]);
}
searchItem(objType, searchKey, arrSize);
}
public static void searchItem(int objType[], int searchKey, int arrSize) {
int i = 0, temp = 10;
for (int j = 0; j < arrSize; j++)
if (objType[i] == temp) {
searchKey = temp;
if (j == arrSize)
System.out.println("Search key not found");
System.out.println("found search key " + searchKey);
}
}
}
最佳答案
您在 j
上进行迭代,但使用 i
进行比较:
for (int j = 0; j < arrSize; j++)
if (objType[i] == temp) {
您也将 searchKey 作为参数传递,但将其用作输出的临时变量,这没有多大意义。
确保你确实想要传递 arrSize,因为你可以使用 objType.length
或增强的 for
(如果你想搜索数组的一部分仍然可以,但是这个名字有误导性,但我怀疑那是你的意图)
那可能是:
public static void searchItem(int arr[], int searchKey) {
int found = 0;
for (int item : arr) {
if (item == searchKey) {
System.out.println("found search key " + searchKey);
found ++;
}
}
if (found == 0) System.out.println("Search key not found");
}
但是,如果找到 key ,您可能想要中断,或者返回找到的 key 数。这样,该方法只产生输出。
关于java - 为什么java中的double if语句返回数组中的空搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33425052/