在 Scanner#nextLine() 收到的不是 "blank space" 或 "enter" 之前,程序不会打印任何内容

Program doesn't print anything until Scanner#nextLine() received not a "blank space" nor "enter"

Scanner in = new Scanner(System.in);
while (in.hasNext()) {
    String a = in.nextLine();
    System.out.println(a + " 1");
}

我只想检查当输入为 SPACE 或 ENTER 时会发生什么,但它不会打印任何内容,直到我的输入既不是 SPACE 也不是 ENTER,就像这样

a                     // input 
a 1                   // output 
                      // SPACE(input) 
c                     // input
  1                   // output
c 1                   // output

为什么它在读取既不是空白也不是 SPACE 的内容之前不打印?此外,当它最终打印时,它会打印 SPACE ,这是 c 1 之前的行,当我输入 c 时,它会给我 1 和 c 1.

正如@Savior 所提到的 :

hasNext() checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter. Since the scanner's delimiter is whitespace, and the linePattern is also white space, it is possible for there to be a linePattern in the buffer but no parseable tokens.

考虑使用 hasNextLine()

public class Main {
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String a = in.nextLine();
            System.out.println(a + " 1");
        }
    }
}

Java Scanner hasNext() vs. hasNextLine():

That is, hasNext() checks the input and returns true if it has another non-whitespace character.
Whitespace includes not only the space character, but also tab space (\t), line feed (\n), and even more characters.
Continuous whitespace characters are treated as a single delimiter.

System.in表示标准输入.
当您通过 System.in 来初始化 Scanner 时,它将从 Standard Input 读取数据.
除非您的输入是 EOF(Ctrl + Z in WindowsCtrl + D).
因此扫描器将始终等待输入的 non-whitespace 字符。

输入

当你按SpaceEnter时,它发送两个whitespace字符 \n 标准输入 ,函数 scanner.hasNext() 仍在等待 non-whitespace 字符。 scanner.hasNext() 没有 return 任何东西。所以此时没有输出。
然后你按下c,它发送non-whitespace字符c标准输入.

输出

现在你的标准输入包含 \nc,第三个不是空格字符.
最后函数 scanner.hasNext() returns true.
然后 scanner.nextLine() 读取一行直到字符 \n:它将是 (一个字符),
和程序打印 1.

标准输入现在变成了c,只有一个字符,
这将导致 scanner.hasNext() 再次变为 return true:
扫描仪将读取一行,这将是一个字符 c,
并打印 c 1.