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

在我的主要方法中是这段代码:


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 块但这次它没有要求我输入并不断从捕获中打印出来并最终阻止,为什么会发生这种情况?


守着一只汪
浏览 460回答 2
2回答

子衿沉夜

因为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;}

茅侃侃

一种更简单的方法是在抛出异常之前测试您是否可以读取 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:");    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java