在 if 中检查 hasNextInt() 然后接收输入

Checking hasNextInt() in if and then receive an input

所以一个简单的程序是:

import java.util.*;
public class practice {
      static Scanner reader = new Scanner(System.in);
      public static void main(String[] args) {

           if(reader.hasNextInt()){

               int numberEntered = reader.nextInt();
           }


      }

}

所以我有一个误会。 hasNextInt() 应该检查下一个输入是否为 int。我看到了这个程序,但我不明白如何输入数字。因为为了获得输入,reader.hasNextInt() 必须为真,而程序还没有获得输入。那么程序如何进入if语句呢?

方法 Scanner#hasNextInt(),在你的例子中,是一个 blocking method。这意味着,它是一种等待并仅在满足某些条件时执行 return 的方法。它看起来像这样:

public boolean hasNextInt() {
    ...
    boolean condition = false;
    while(!condition) {
        ...
    }
    ...
    return stuff;
}

更准确的说,屏蔽方式是Scanner#hasNext()。它在其 documentation 中进行了描述。 该方法是否阻塞取决于 Scanners 来源。如果是,例如 System.in,它将等待。如果它只是一个File,它会读取整个文件直到结束然后return,没有阻塞。

那么,会发生什么? if-condition 中的 hasNextInt 等待您输入一些内容(直到您通过键入 Enter 发送它)。然后 Scanner 将输入保存在缓冲区中。 hasNextInt 检查内部缓冲区但不从缓冲区中删除内容。

现在 nextInt 从内部缓冲区读取并删除其中的内容。它推进过去的阅读输入

你可以在上面提到的文档中详细阅读。

Things short: Scanner#hasNextInt() 在它之前等待输入 returns true or false.