首页 > Java基础Scanner类nextInt方法的问题

Java基础Scanner类nextInt方法的问题

这个是我所问问题的代码

import java.util.*;
public class Practice {
    public static String prompt = "How are you? ";
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        System.out.print(prompt);
        //int year=getYourAge(console);
        System.out.println("Your age is "+getYourAge(console));
    }
    public static int getYourAge(Scanner console){
        while(!console.hasNextInt()){
            console.next();
            System.out.println("Not an integer;try again!");
            System.out.print(prompt);
        } 
        return console.nextInt();
    }
}

我想问的问题是,当程序执行到return语句的时候,为什么不等待用户的新一次输入呢?而是直接返回上一次的输入结果。
比方说:

当我输入18的时候,程序跳出While循环,进入return语句,为什么不等待我新的一次输入,而是直接返回18?
平时无论我们何时使用ScannerObjext.nextInt();的时候都会等待一次输入,为什么在这里就不等待了呢?

谢谢回答的各位!


Hasnext阻塞但不影响当前的缓冲区偏移量
然后当if为否的时候 整形的一段值已经在缓冲区中的偏移量后了

【热门文章】
【热门文章】