总体而言,对于 java 和 oop 来说非常陌生。所以要友善。
我有一个包含 10 个整数的文本文件,searchkeysArray.txt。该程序创建一个名为keysArr的数组。我还有另一个包含 500 个随机整数的文本文件,array1.txt。该程序创建了另一个名为 array1 的数组。
我想使用我创建的 LinearSearch 方法来搜索 array1 中 keysArr 的元素并输出它存在的索引。
public static int linearSearch(int arr[], int x)
{
int size = arr.length;
for(int i = 0; i < size; i++)
{
if(arr[i] == x)
return i;
}
return -1;
}
读取文件方法
public static int[] readFile(String file)
{
try {
File f = new File(file);
Scanner s = new Scanner(f);
int ctr = 0;
while (s.hasNextInt())
{
ctr++;
s.nextInt();
}
int[] arr = new int[ctr]; //create array of that size
Scanner scanner2 = new Scanner(f);
for (int i = 0; i < arr.length; i++)
arr[i] = scanner2.nextInt();
return arr;
}
catch(Exception e)
{
return null;
}
程序。
public static void main(String[] args)
{
int[] keysArr = readFile("searchkeysArray");
int[] array1 = readFile("array17");
int key = 34;
int result = linearSearch(array1, key);
if (result != -1)
System.out.print("The element " +key+" is present in the array, at index " + result + " ");
else
System.out.print("The element " +key+" is not present in the array ");
}
它输出
The element 34 is present in the array, at index 359
这是有道理的。我已经手动测试了数字并且(显然)一切正常。但我不太明白我应该如何使用keysArr 作为我的 key 而不是int x = some number。
想要输出类似的内容
The element [keysArr[0]] is present in the array, at index 359
The element [keysArr[1]] is present in the array, at index 547
...
The element [keysArr[4]] is not present in the array
等等。 现在,keysArr 只是一个包含 10 个整数的数组,但我最终将使用数百个..
最佳答案
您希望循环遍历键数组 keysArr
,而不是使用特定的硬编码键,例如 int key = 34
。您可以通过使用如下代码来实现:
for (int key : keysArr) {
int result = linearSearch(array1, key);
if (result != -1)
System.out.print("The element " +key+" is present in the array, at index " + result + " ");
else
System.out.print("The element " +key+" is not present in the array ");
}
关于Java 搜索数组中存在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54174003/