Vaak
Vaak

Reputation: 39

java find a specific line in a file based on the first word

I have a file that I am importing and what I want do is ask for the user's input and use that as the basis for finding the right line to examine. I have it set up like this:

     public class ReadLines {
    public static void main(String[] args) throws FileNotFoundException
    {
         File fileNames = new File("file.txt");
     Scanner scnr = new Scanner(fileNames);
     Scanner in = new Scanner(System.in);

    int count = 0;
    int lineNumber = 1;

    System.out.print("Please enter a name to look up: ");
    String newName = in.next();

    while(scnr.hasNextLine()){
          if(scnr.equals(newName))
          {
              String line = scnr.nextLine();
              System.out.print(line);
          }
      } 
}

Right now, I am just trying to get it to print out to see that I have captured it, but that's not working. Does anyone have any ideas? Also, if it matters, I can't use try and catch or arrays. Thanks a lot!

Upvotes: 1

Views: 145

Answers (2)

Roney Gomes
Roney Gomes

Reputation: 507

I'd do something in the lines of:

Scanner in = new Scanner(System.in);

System.out.print("Please enter a name to look up: ");
String name = in.next();

List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();

if (firstResult.isPresent) {
    System.out.print("Line: " + firstResult.get());
} else {
    System.out.print("Nothing found");
}   

Upvotes: 0

gonzo
gonzo

Reputation: 2121

You need to cache the line in a local variable so you can print it out later. Something like this should do the trick:

while(scnr.hasNextLine()){
    String temp = scnr.nextLine(); //Cache variable
    if (temp.startsWith(newName)){ //Check if it matches
        System.out.println(temp); //Print if match
    }
}

Hope this helps!

Upvotes: 1

Related Questions