I have file with a list of names in it and next to the names is a series of digits. The digits represent its level of popularity per every 10 years.

The program I have asks the user to input the file path, then it asks for the user to input a name. The program needs to search the file for the name that was entered. Once the name has been located it needs to print out the name and the numbers on separate lines.

Ex.
file has:
Laura 0 0 1 143 443 100 3 43 12 555 0 0
Lisa 900 1 200 22 4 1 1 45 89 0 0 2

User Input:
Enter Name: Lisa
Name found - Lisa
1900: 900
1910: 1
1920: 200
1930: 22
1940: 4
etc, etc.

I can get it to read the file, but it prints the entire file. I need it to just read out the name that was entered (if it exists) and the stats with it.

Here is my code (I have also included the txt file):

What are the best changes to make? I am new to doing this in any code language.

package babynames;

import java.util.*;
import java.io.*;

public class BabyNames
{
    public static void main(String[] args)
    {
        Scanner userInput = new Scanner(System.in);
        System.out.print("Enter file path: ");
        File file = new File(userInput.nextLine());
        
        Scanner userInput2 = new Scanner(System.in);
        System.out.print("Enter name: ");
        String name = userInput2.nextLine();

        StringBuffer contents = new StringBuffer();
        BufferedReader reader = null;

        try
        {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            while ((text = reader.readLine()) != null)
            {
                contents.append(text).append(System.getProperty("line.separator"));

            }
        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if(reader != null)
                {
                    reader.close();
                }
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }

        System.out.println(contents.toString());

    }//close main
}

Use split() method of String.

.....
            String []items=null;
            boolean found=false;
            while (!found && (text = reader.readLine()) != null)
            {
               items=text.split(" ");
               if(items[0].equals(name)) 
                   found=true;

            }
            if(found){
            for(String v:items){
              System.out.println(v); 
             }
            }
          ....
commented: This worked great!! Thanks!! +1