1

我正在尝试在数组中查找一个值,并且我确定该值将只存在一次,因此我正在尝试查找该值并返回存储它的数组的索引,如果未找到则返回 -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;

    }

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

4

8 回答 8

7

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

在您的情况下,我建议您使用数组int而不是Integer,它在内存、支持方面更轻,==并且您没有使用 的任何功能,Integer因此您在这里不需要它们。

于 2012-08-22T08:00:13.457 回答
4

您在检查时检查身份operator==(两个引用是否指向完全相同的对象?)而不是相等性(它们是否彼此相等?)。

您应该使用ints(而不是Integers)或更改条件以使用该equals()方法。

于 2012-08-22T08:00:26.437 回答
2

Integer 是一个对象,所以你必须使用 equals 方法。试试 numbers[index].equals(key)。

于 2012-08-22T08:00:09.820 回答
1
java.util.Arrays.asList(accs).indexOf(key)  

或者

org.apache.commons.lang.ArrayUtils.indexOf(accs, key);
于 2012-08-22T08:02:01.647 回答
0

使用以下命令捕获用户输入 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

于 2012-08-22T10:15:51.730 回答
0

确保您了解对象相等和对象标识之间的区别。您正在使用“==”来检查您的值是否在数组中 - 这将检查身份,而不是平等。改为使用numbers[index].equals(key)

于 2012-08-22T08:01:41.787 回答
0

在搜索之前,您需要为每个元素设置值。下面的语句仅声明具有 20 个元素的新数组 value = null static Integer[] accs = new Integer[20]; 替换为: static Integer[] accs = new Integer[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; 并重新测试。

问候,

于 2012-08-22T08:16:37.797 回答
0

像这样初始化数组并在main中static Integer[] accs = {3,5,15,6,4,32,9};调用 方法。search()您的功能正常工作。

于 2012-08-22T08:23:41.063 回答