hasNextLine() 在 While 循环中总是返​​回 true

hasNextLine() always returning true within While Loop

这个问题链接到我之前问过的关于同一程序的问题,可以在这里查看:

Writing to a file code causing an endless loop

我已经解决了上面的问题,并将函数重写为 while 循环而不是 do while,但是现在我遇到了相反的问题,即没有任何内容写入文件。我插入了一个打印语句来告诉我 hasNextLine 的状态,它总是返回 true,即使输入了一个空行,也就是我希望 writer 终止的时候。

这是更新后的代码:

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;;

public class Lab_Week8_WriteAStory {
    public static void main(String[] args) throws FileNotFoundException  {  

        Scanner whatToWrite = new Scanner (System.in);
        PrintWriter writing = new PrintWriter ("Read and Write Files/output.txt");

        while (whatToWrite.hasNextLine()){
            String writeToFile = whatToWrite.nextLine();
            writing.println(writeToFile);
            System.out.println (whatToWrite.hasNextLine());
        }

        writing.close();
        whatToWrite.close();
    }
}

查看 Scanner.hasNextLine() 的文档:

Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

这就是正在发生的事情。由于您使用 System.in 作为输入源,该方法正在等待您的输入,一旦您提供输入,它就会 returns 为 true 并继续到下一行并重复该过程。