I am implementing sequential search using Java.
I am trying to search string from a string array. The query is obtained from keyboard using nextLine()
. However I always get "not found" even when the string is clearly in the list.
/**
Implementing sequential search
*/
public class SequentialSearch {
public static boolean sequentialSearch(String[] names, String query) { //static method takes a string array and the query as arguments
for (String x: names) //traverse the list
if (x == query) {
System.out.println("found");
return true;
} //end if
System.out.println("not found"); //end for
return false;
} //end method
} //end class
class TestSequentialSearch {
public static void main (String[] args) {
String[] names = {"John", "Amy", "Tom", "Jay", "Olivia", "Jack", "Peter", "Emma"}; //a new name list
Scanner in = new Scanner(System.in);
String x;
System.out.println(Arrays.toString(names));
System.out.println("name to be searched: ");
while (in.hasNextLine()) {
x = in.nextLine();
SequentialSearch.sequentialSearch(names, x); //search input in the list
System.out.println("name to be searched: ");
} //end while
} //end main
} //end test