我正在使用Java實現順序搜索。 我想從字符串數組中搜索字符串。查詢是通過鍵盤使用nextLine()
獲得的。但是,即使字符串清楚地顯示在列表中,我總是會「找不到」。使用Scanner.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
非常感謝,夥計們。有效! – user2487232
@ user2487232很高興知道這一點。你可以通過點擊答案左邊的勾號來接受答案。 –