Reputation: 59
Below I have code which puts separate lines from a text file into an array. It asks the user to type in a string, and subsequently looks for the string in the array and see if the strings equals an element of the array. If so, it says it does and says which element it equals, and if not it says it could not find it. However, this code always says it can't find the line even though I can clearly see that the input equals an element from the array. What is incorrect here? I have no clue where the problem lies so below is the code for creating the array and the linear search algorithm:
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);
}
}
Upvotes: 0
Views: 238
Reputation: 771
The problem might lay in the following code snippet:
Array[pos]== line
The comparison here is done using the references and not the actual content of the String. This behavior works fine for string literals and String values which are explicitly interned (and stored in the Java string pool). You might also check out following link : https://dzone.com/articles/string-interning-what-why-and
I would suggest to use String.equals() for comparing the values. Hope this helps.
Upvotes: 0
Reputation: 361
In your while loop use equals
method for String comparison instead of ==
==
works on Strings iff they are both constants (created like "XXX"
). If they are created like new String("Test")
they are not constants so:
new String("A") == new String("A")
will produce false, but new String("A").equals(new String("A"))
will produce true
"A" == "A"
will produce true and "A".equals("A")
will produce true aswell
Upvotes: 2