如果在数组中找到值,则返回Java索引

Jac*_*Boi 1 java arrays search

我试图在数组中找到一个值,我确定这个值只存在一次,所以我试图找到该值并返回存储它的数组的索引,如果没有找到返回-1这是我想要做的:

static Integer[] accs = new Integer[20];
 public static int search()
    {
        Integer[] numbers;
        numbers = accs;
        Integer key;
        Scanner sc = new Scanner(System.in);
         System.out.println("Enter the Account Number:");        
         key = sc.nextInt();

        for (Integer index = 0; index < numbers.length; index++)
      {
           if ( numbers[index] == key )
                 return index;  //We found it!!!
      }
     // If we get to the end of the loop, a value has not yet
     // been returned.  We did not find the key in this array.
     return -1;

    }
Run Code Online (Sandbox Code Playgroud)

当我运行它时,即使我知道数组中存在该值,也没有显示任何内容.我调试了然后我发现Key变量没有我键入的值.有什么不对吗?

jol*_*ier 7

您的数组存储Integer,它是一个java对象,用于测试您需要调用Object.equals方法的Java Object的相等性,而不是==.

在你的情况下,我建议你使用一个数组int而不是Integer,它更轻松的内存,支持==,你没有使用任何功能,Integer所以你不需要它们在这里.