scanner.hasNext()说明

public class Demo01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if(scanner.hasNext()){
            String next = scanner.next();
            System.out.println(next);
        }
        scanner.close();
    }
}

最初看到scanner.hasNext()的使用时,不免产生疑惑,为什么本该一闪而过的if判断能够等待我的输入。

查询JDK手册,hasNext():Returns true if this scanner has another token in its input.

当执行到hasNext()时,它会先扫描缓冲区中是否有字符,有则返回true,继续扫描。直到扫描为空,这时并不返回false,而是将方法阻塞,等待你输入内容然后继续扫描。

posted @ 2020-12-20 09:40  飒飒阿萨德  阅读(411)  评论(0)    收藏  举报