java - 为什么java中的double if语句返回数组中的空搜索

标签 java arrays

我在 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/

相关文章:

java - 通过 JNI 从 Java 使用 CoreBluetooth 时未调用 didDiscoverCharacteristics

java - 在 android studio 中从基于 Web 的应用程序打印?

arrays - 数组中的通配符搜索

php - 最好的方法是什么?

javascript - 确定牌 table 位置 - Sit'n Go 锦标赛

javascript - 从常规数组创建新的二维数组

java - 未转义的 "."在否定组中使用时仍然匹配

java - Hibernate 翻译功能

java - 想要使用比较器按时间戳对 ArrayList 中的聊天进行排序,但它不起作用,我不知道为什么

java - 为什么该算法执行IF语句时没有错误?