首页 文章

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

提问于
浏览
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变量没有我输入的值 . 那里有什么不对吗?

8 回答

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

    要么

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

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

  • 4

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

    问候,

  • 7

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

  • 0

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

  • 1

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

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

  • 2

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

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

  • 0

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

相关问题