我试图在一个数组中找到一个值,我确信这个值只会存在一次,所以我试图找到这个值并返回存储它的数组的索引,如果找不到则返回-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 变量没有我输入的值。有什么问题吗?
最佳答案
您的数组正在存储 Integer,它是一个 Java 对象,用于测试您需要调用 Object.equals 的 Java 对象是否相等。方法而不是 ==
。
在你的情况下,我建议你使用 int
数组而不是 Integer
,它在内存中更轻,支持 ==
并且你没有使用 Integer
的任何功能,因此您在这里不需要它们。
关于如果在数组中找到值,则 Java 返回索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12068651/