# Using Linear Search to find multiple indexes

• 03-16-2011, 04:52 PM
Roberto1989
Using Linear Search to find multiple indexes
Okay first of all, yes this is homework which I have been asked to complete. Help which I am asking for with this is to simply point me in the right direction.

What I have asked to do is to use linear search to find a value in an array (let's say for example that the number was 6) and then to find all of the indexes in which 6 appears in the array.

int[] a = [3, 2, 6, 1, 0, 0, 6]

so the result which I should receive should be 2 and 6 as those are the positions in which 6 appears. (Also need a return value if it isn't in the list but I can do that.)

My logic is to run a for loop in the method that is responsible for searching the array and to print it. This does work but my issue here now is that -1 (this is the flag that says that the value is not present in the array) is always returned to the main method which means that as far as the program is concerned, every time the program is executed, there are never any indexes found from the search.

Example of what is printed on screen:

[3, 2, 6, 1, 0, 0, 6]
enter a value to search:> 6
2 6 The specific value which you have searched for is not present in this array.

I hope I have been clear and thank you for your time.
• 03-16-2011, 05:36 PM
ozzyman
Code:

```//define list to search int[] a = {3, 2, 6, 1, 0, 0, 6}; //define number to find in list int searchTerm = 6; //define a List because we don't know how many answers there will be so we can't use an Array java.util.List<int> answer = new java.util.ArrayList<int>(); //for each integer item in the array "a"; int i=a for (int i:a) {   //if i=6, add to our List   if (i == searchTerm) answer.add(i); } //print our list using the Java Formatter for (int i:answer) {   System.out.printf("We found %d at location %d%n",searchTerm,i); }```
In case you are unfamiliar with "printf", the first %d is replaced by searchTerm, and the second %d is replaced by i, and %n makes a line break like "println" does.