while循环条件又是如何重新求值的

How is the while loop condition re-evaluated again

我看到了下面的代码片段

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scan=new Scanner(System.in);
        boolean flag = scan.hasNext();
        while(flag){
            System.out.println(scan.nextLine());
        }
        System.out.println("End");
    }
}

一旦分配了值 true 或 false 的布尔标志不应再次更改,但我发现每当我在终端中键入内容时,while 循环都会再次执行。

有人可以解释一下每当我在终端中输入内容时如何重新评估标志吗?

注意:我的问题不是关于 stopping/closing 扫描器,而是关于了解如何重新评估循环条件。

我认为您在这里遇到的是scan.hasNext()阻塞,直到您第一次输入。

那么,标志永远为真。

进入循环后,您将打印下一行,但 scan.nextLine() 也会阻塞,直到您提供 EOL,即带有行尾的输入。