为什么我的扫描仪 hasNext("string") 方法提示输入?

Why does my scanner hasNext("string") method prompt for input?

我知道 hasNext() 用于检查是否有下一个输入,但我的 hasNext 出于某种原因提示输入。这是我的代码:

Scanner sc = new Scanner(System.in);

while (!sc.hasNext("quit")) {
    System.out.println("Type anything other than quit to keep inputting. ");
    sc.nextLine();
}

我的程序立即执行的操作是让我键入内容(在提示键入之前),然后弹出 "type anything other than quit" 的提示并且程序正常运行。但是,我不想要第一个空白输入。为什么会弹出这个问题,我该如何解决?

Scanner-API

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

因此,您将在输入一行后进入 while-body。

写类似

String next = "";
while (!next.equals("quit")) {
    System.out.println("Type anything other than quit to keep inputting. ");
    next = sc.nextLine();
}