I don’t see much here which really surprises me. Most likely, the end of the file gets reached in your while
loop with the first call to Scanner#nextLine()
. Then, you make a second call which throws the exception since there is no more content to read.
while (reader.hasNextLine()) {
// during the last iteration, this next call consumes the final line
String line = reader.nextLine();
if (word.isEmpty()) {
// but then you call nextLine() here again, causing the exception
//System.out.println(reader.nextLine());
System.out.println(line);
}
}
The moral of the story here is to not read content from your Scanner
without first checking that content is there. By commenting out the above line, you removed the problem, but you should understand why it is probably good that you commented it out.
solved Reading text files in java