Java .hasNext()无法正常工作

Java .hasNext()无法正常工作,java,Java,当我运行此代码并输入: 嗨 在控制台中打印这些内容: Scanner scanner = new Scanner(System.in); // check if the scanner has a token System.out.println(scanner.hasNext()); // print the rest of the string System.out.println(scanner.nextLine()); // check

当我运行此代码并输入:

在控制台中打印这些内容:

    Scanner scanner = new Scanner(System.in);
    // check if the scanner has a token
    System.out.println(scanner.hasNext());

    // print the rest of the string
    System.out.println(scanner.nextLine());

    // check if the scanner has a token after printing the line
    System.out.println(scanner.hasNext());
但程序从未结束或打印
false
。有什么问题

true
Hi
hasNext()
在等待输入时阻塞。这就是为什么第二次调用
System.out.println(scanner.hasNext())不打印任何内容,程序不会结束


如果扫描仪是从文件而不是从标准输入读取数据,
hasNext()
到达文件末尾时将返回false。

您是从控制台读取数据,这就是它不返回false值的原因。与其尝试从文件中读取数据,它肯定会工作,因为当文件读取到达文件末尾时,它将返回false,因为没有值。

除了@Eran的答案外,请注意扫描仪不仅用于从System.In读取数据,还可以从文件中读取数据。在这种情况下,它可能会打印我想要的假图像“while(scanner.hasNext()”,那么我能做什么?@KaavehMohamedi从标准输入读取输入时,可以选择一些标记输入结束的输入。例如:`while(!(line=scanner.nextLine()).equals(“quit”))是的,没错!但当我在CodeForces.com或其他竞争性编程中解决问题时,我不能选择。@KaavehMohamedi也许你们应该详细说明你们的代码应该做什么。代码的输入应该来自标准输入吗?您可以看到:编写一个程序,列出输入文本中的所有不同单词。输入:输入为不超过5000行的文本。一个输入行最多有200个字符。输出:您的输出应该给出输入文本中出现的不同单词的列表,一行一个。您可以确保文本中不同单词的数量不超过5000。示例输入:迪斯尼乐园历险记两个金发女郎正要去迪斯尼乐园,这时她们来到了一个岔路口。牌子上写着:“迪斯尼乐园离开了。”于是他们回家了。
/**
 * Returns true if this scanner has another token in its input.
 * This method may block while waiting for input to scan.
 * The scanner does not advance past any input.
 *
 * @return true if and only if this scanner has another token
 * @throws IllegalStateException if this scanner is closed
 * @see java.util.Iterator
 */
public boolean hasNext()