Java基础Scanner类nextInt方法的问题
怪我咯
怪我咯 2017-04-17 15:18:15
[Java讨论组]

这个是我所问问题的代码

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();的时候都会等待一次输入,为什么在这里就不等待了呢?

谢谢回答的各位!

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
PHPz

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号