我正在使用 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
最佳答案
使用equals()方法而不是 == 进行字符串比较。 as equals 检查字符串内容是否相等,而 == 检查对象是否相等。更改代码 if
条件:
来自
if (x == query)
至
if (x.equals(query))
从此处的相关文章中了解有关字符串的 equals 和 == 比较之间的区别的更多信息:
关于java - 使用 Scanner.nextLine() 从输入(键盘)读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17514013/