ソートされた配列で線形に検索し、検索されたアイテムが見つかったさまざまな位置を出力できるプログラムを作成したいと考えています。現時点では、私のプログラムは検索項目が見つかった最初の位置のみを出力するため、私のプログラムが現在行っていることの例を次に示します。
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.");
}
}