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);
}
}