我正在使用 Java 实现顺序搜索。我正在尝试从字符串数组中搜索字符串。查询是使用键盘从键盘获取的nextLine()
。但是,即使字符串清楚地在列表中,我也总是得到“未找到”。
/**
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