我想制作一个程序,在排序数组中进行线性搜索,并可以输出找到搜索项的不同位置。目前,我的程序仅输出找到搜索项的第一个位置,因此这里是我的程序现在所做的示例:
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.");
}
}
最佳答案
...
System.out.println("Enter value to find");
search = in.nextInt();
boolean exists = false;
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
exists = true;
}
}
if (!exists) /* Searching element is absent */
System.out.println(search + " is not present in array.");
您需要删除break;
语句。否则,一旦找到第一个值,循环就会中断,并且永远不会到达下一个匹配项。
关于java - 排序数组中的线性搜索 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34452878/