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.