我想制作一个程序,在排序数组中进行线性搜索,并可以输出找到搜索项的不同位置。目前我的程序只输出找到搜索项的第一个位置,所以这是我的程序现在所做的一个例子:
Enter number of elements
5
Enter 5 integers
1
3
3
9
15
Enter value to find
3
3 is present at location 2.
现在问题是 3 在位置 2 和 3,这就是我想在程序中编辑的内容,但我不知道该怎么做。
这是我的程序的代码:
import java.util.Scanner;
class LinearSearchArray1 {
public static void main(String args[]){
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}