0

Just for context I am working on MOOC Object-Oriented Programming with Java, Week 9 exercise 21: Printer.

In this exercise I am making a Printer class which can receive any file input to its constructor parameter to print out text.

In the method printLinesWhichContain(String word), I need to, using a Scanner, print lines of a file which only contain the word in the parameter.

public void printLinesWhichContain(String word){
    if(!word.equals("")){
        String string = "";
        while(reader.hasNextLine()){
            String line = reader.nextLine();
            if(line.contains(word)){
                string += line;
                string += "\n";
            }
        }
    System.out.println(string);
    }
    else {
        printAll();
    }
    reader.close();
}

If I run my program once with multiple of the above method, the first method works, with the others receiving a Scanner closed error. Example below...

Printer printer = new Printer("src/textfile.txt");

printer.printLinesWhichContain("on"); //this works
printer.printLinesWhichContain("vanha"); //Scanner closed
printer.printLinesWhichContain("tuli"); //Scanner closed

I have no idea how a Scanner works. The Scanner is closing as programmed but once I need to use it again, it's inaccessible. reset() method doesn't help lol. Even if the close() method isn't coded, it doesn't want to print out the rest as, what I could guess, the Scanner's "line" has permanently "moved" with nextLine(). I need a little explanation.

  • As you suspect, a given Scanner instance will only read through its input once. You haven't shown the constructor of `Printer`, but I suppose you are creating the `Scanner` there. Can you think of a different place to create the `Scanner` so that each time `printer.printLinesWhichContain()` runs it gets a new `Scanner`? – tgdavies Jul 05 '20 at 07:24
  • You can't "rewind" a `Scanner`. Once it has scanned the whole file, it can't be re-used to scan the same file again. You have to create a new `Scanner`. There are alternatives to `Scanner` but you indicated that the exercise stipulates that you must use a `Scanner` so not much point in detailing the alternatives. – Abra Jul 05 '20 at 07:49
  • check this https://stackoverflow.com/questions/33555283/why-is-not-possible-to-reopen-a-closed-standard-stream/33555444 – maksoud Jul 05 '20 at 07:58

0 Answers0