I am reading a file line past line using Scanner. And then my question is how tin can I as well store the previous line next as we keep on moving to adjacent line.

                              while (scanner.hasNextLine()) {     line = scanner.nextLine();//this volition go the current line     if (line.contains("path=/select")){     // So whenever I enter in this if loop or this loop is truthful, I also desire to      have the  previous line in whatever String variable. How tin we achieve this?      }                          

Whatsoever suggestions will be appreciated.

asked Dec 7, 2011 at half-dozen:01

2 Answers 2

                  Cord previousLine = zippo; while (scanner.hasNextLine()) {     String line = scanner.nextLine();     if (line.contains("path=/select")) {         // utilise previousLine here (nada for the first iteration or grade)     }     previousLine = line; }                                  

answered Dec 7, 2011 at 6:03

0

                  prevLine = null; // null indicates no previous lines  while (scanner.hasNextLine()) {     line = scanner.nextLine(); //this volition get the current line     if (line.contains("path=/select") && prevLine != null){         // ...     }     prevLine = line; }                                  

I'm bold that if there's no previous line, and so you lot wouldn't want to enter the if block.

answered Dec 7, 2011 at 6:04

two

  • Your examination for line != nix is completely pointless. Run across if yous can effigy out why

    Dec seven, 2011 at 6:07

  • @Bohemian: woops that was supposed to exist prevLine to correspond with the text below the code... :/

    Dec 7, 2011 at 6:10

Not the respond you're looking for? Scan other questions tagged java java.util.scanner or inquire your ain question.