【问题标题】:ask for an input until he enters a number? [duplicate]要求输入,直到他输入一个数字? [复制]
【发布时间】:2016-06-20 04:49:18
【问题描述】:
do{
    try{
        System.out.println("Please enter the publication year :");
        year=keyboard.nextInt();
        doneYear=true;
    } catch(InputMismatchException e) {
        System.out.println("Please enter a number.");
    }
} while(!doneYear);

这不起作用。一旦遇到第一个异常,它就会无限循环。

【问题讨论】:

  • 我认为你的 catch 块中需要keyboard.next()

标签: java input integer java.util.scanner


【解决方案1】:

nextXYZ() 方法(特别是在您的情况下为 nextInt())如果以 InputMismatchException 失败,则不会使用令牌。如果发生这种情况,您需要消耗当前的错误令牌才能继续并获取新令牌。否则,您将继续重新评估,重新失败相同的输入,导致您观察到的无限循环:

do {
    try {
        System.out.println("Please enter the publication year :");
        year = keyboard.nextInt();
        doneYear = true;
    } catch (InputMismatchException ignore) {
        keyboard.nextLine(); // consume and ignore current input
        System.out.println("Please enter a number.");
    }
} while (!doneYear);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2021-05-14
    • 1970-01-01
    • 2014-12-18
    • 2012-07-24
    • 2011-10-02
    相关资源
    最近更新 更多