尝试在数组中查找字符串,但线性/顺序搜索不起作用



下面我有代码将文本文件中的单独行放入数组中。它要求用户键入一个字符串,然后查找数组中的字符串,并查看字符串是否等于数组的一个元素。如果是这样,它说它有,并说它等于哪个元素,如果不是,它说它找不到它。但是,这段代码总是说它找不到该行,即使我可以清楚地看到输入等于数组中的一个元素。这里有什么不正确的?我不知道问题出在哪里,所以下面是创建数组和线性搜索算法的代码:

public static void main(String[] args) throws FileNotFoundException
{ 
File file = new File("text.txt"); //puts separate lines of file into an array
Scanner text = new Scanner(file);
String[] Array = new String[10];
for (int i = 0; i < 10 && text.hasNextLine(); i++) 
{
    String line = text.nextLine();
    if (line.isEmpty()) 
    {
        continue;
    }
    Array[i] = line;
    System.out.printf("Element %d of the array is: %s%n", i, Array[i]);
}

Scanner input = new Scanner(System.in); //performs sequential search based on user input 
System.out.println("Type the line you want to find: ");
String line = input.next();
int pos = 0;
boolean found = false;
while (pos < Array.length && !found)
{
    if(Array[pos]== line)
    {
        found = true;
    }
    else 
    {
        pos++;
    }
}
 if (found)
 {
     System.out.println("Found at position: " + pos); 
 }
 else 
 {
     System.out.println("Could not find " + line); 
 }
}

在你的 while 循环中使用equals方法进行字符串比较而不是==

== 在字符串上工作,如果它们都是常量(像 "XXX" 一样创建(。如果它们像new String("Test")一样创建,则它们不是常量,因此:

new String("A") == new String("A")会产生,但new String("A").equals(new String("A"))会产生

"A" == "A"将产生真实"A".equals("A")也将产生真实

问题可能出在以下代码片段中:

Array[pos]== line

此处的比较是使用引用而不是字符串的实际内容完成的。此行为适用于显式驻留(并存储在 Java 字符串池中(的字符串文本和字符串值。您也可以查看以下链接:https://dzone.com/articles/string-interning-what-why-and

我建议使用 String.equals(( 来比较值。希望这有帮助。

最新更新