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

    }
}

Did you look up the meaning of the -1 returned value?

Print out the String that is being searched and the String you are looking for so you can see what the computer is seeing. Be sure to surround the String with delimiters at each end. For example: ">" + string + "<"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.