I am trying to write a program that will allow the user to search for a first or last name within a document full of people's names, and respond with the position of that name within the .txt file. What I have right now keeps returning -1 for the position and I'm not sure what's wrong. Any help would be much appreciated.
import java.io.*;
import java.util.Scanner;
class SearchFunction {
public static void main(String[] args)
{
//prompts user for name to search for
Scanner input = new Scanner (System.in);
System.out.println("Who would you like to search for (family or given name)?");
String searchText = input.nextLine();
//chooses the name.txt document to search through
String fileName = "names.txt";
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
//Reads until the end of the file
while (reader.ready())
{
//Read line-by-line
sb.append(reader.readLine());
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
String fileText = sb.toString();
System.out.println("Position in file : " + fileText.indexOf(searchText));
}
}