为了账号安全,请及时绑定邮箱和手机立即绑定

Scanner 类的 nextInt() 方法不会在 while 循环中再次要求我输入?

Scanner 类的 nextInt() 方法不会在 while 循环中再次要求我输入?

守着一只汪 2022-01-12 15:58:08
在我的主要方法中是这段代码:int hours = getHours();这是获取 hours() 代码:public static int getHours() {    int hours = 0;    boolean hoursNotOk = true;    do {    try {        hours = console.nextInt();        hoursNotOk = false;    }catch(Exception e) {        System.out.print(e);    }finally {        if(hoursNotOk) {            System.out.print(", please re-enter the hours again:");        }else {            System.out.print("**hours input accepted**");        }    }    }while(hoursNotOk);    return hours;}第一次 console.nextInt() 要求我输入,所以假设我在控制台中输入了一个“2”,它会抛出一个异常并再次循环通过 try 块但这次它没有要求我输入并不断从捕获中打印出来并最终阻止,为什么会发生这种情况?
查看完整描述

2 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

因为nextInt()只读取数字,而不是按\n回车后附加的,所以在再次读取数字之前需要清除它,在这个例子中我nextLine()在catch块中做。这里有更深入的解释


工作示例:


public static int getHours() {

    int hours = 0;

    boolean hoursNotOk = true;


    do {

        try {

            System.out.println("Here");

            hours = console.nextInt();

            hoursNotOk = false;


        } catch (Exception e) {

            e.printStackTrace();

            console.nextLine();

        } finally {

            if (hoursNotOk) {

                System.out.println(", please re-enter the hours again:");


            } else {

                System.out.println("**hours input accepted**");


            }

        }

    } while (hoursNotOk);


    return hours;

}


查看完整回答
反对 回复 2022-01-12
?
茅侃侃

TA贡献1842条经验 获得超22个赞

一种更简单的方法是在抛出异常之前测试您是否可以读取 int。在任何情况下,您都需要在重试之前丢弃当前的单词或行。


public static int getHours() {

    while (true) {

        if (console.hasNextInt()) {

            System.out.print("**hours input accepted**");

            return console.nextInt();

        }

        console.nextLine(); // discard the line and try again

        System.out.print(", please re-enter the hours again:");

    }

}


查看完整回答
反对 回复 2022-01-12
  • 2 回答
  • 0 关注
  • 459 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号