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

时间:2012-08-22 07:57:01

标签: 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;

    }

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

8 个答案:

答案 0 :(得分:7)

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

在您的情况下,我建议您使用int而不是Integer的数组,内存更轻,支持==并且您没有使用{{Integer的任何功能1}}所以你在这里不需要它们。

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

Integer是一个对象,因此您必须使用equals方法。尝试数字[index] .equals(key)。

答案 3 :(得分:1)

java.util.Arrays.asList(accs).indexOf(key)  

org.apache.commons.lang.ArrayUtils.indexOf(accs, key);

答案 4 :(得分:0)

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

答案 5 :(得分:0)

在搜索之前,您需要为每个元素设置值。 下面的语句只声明带有value = null的20元素的新数组 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}; 并重新测试。

此致

答案 6 :(得分:0)

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

答案 7 :(得分:0)

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

相关问题