I'm working on a homework assignment that asks to write a method called linearSearch that performs a linear search on an integer array: searches starting at index 0, then 1, 2, 3…. It should return the index of the array that contains the target or a -1 if it is not found in the array. I have done that but an issue that I am seeing is if the target appears more than once in the array the print statement will only print where it's located first. For Example, if my array is [6, 3, 9, 2, 7, 6]. The print statement says "6 is found at index: 0". Is there a way to change it when the value appears more than once so the print statement will then say "6 is found at index: 0 and 5"?
import java.util.Arrays;
import java.util.Random;
public class Q6 {
public static void main(String[] args) {
Random random = new Random();
int x = random.nextInt(10);
int[] y = createRandomIntArray(x);
int z = x;
System.out.println(Arrays.toString(y));
System.out.println(z + " is found at index: " + linearSearch(y, z));
}
public static int[] createRandomIntArray(int n) {
Random random = new Random();
int[] result = new int[n];
for (int i = 0; i < result.length; i++)
result[i] = random.nextInt(10);
return result;
}
public static int linearSearch(int[] array, int target) {
for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1;
}
}
Output:
[6, 3, 9, 2, 7, 6]
6 is found at index: 0
Aucun commentaire:
Enregistrer un commentaire