【问题标题】:Scanner doesn't read user input after exception异常后扫描仪不读取用户输入
【发布时间】:2014-09-10 11:57:06
【问题描述】:

为什么异常发生后 Scanner 不读取值?这是代码。当抛出异常时,在下一次迭代中它不允许用户输入数据,它总是转到 catch 块并打印文本。

public class Main {
    public static void main(String[] args) {
        Scanner inputScanner = new Scanner(System.in);
        boolean correctInput = false;
        do {
            try {
                int readInt = inputScanner.nextInt();
                correctInput = true;
            } catch (InputMismatchException e) {
                correctInput = false;
                System.out.println("Please enter int value");
            }
        } while (!correctInput);

    }
}

【问题讨论】:

  • 不要使用异常来控制代码流。请改用while(!scanner.hasNextInt())

标签: java


【解决方案1】:

nextInt 不使用非整数值,因此一旦发生异常,任何此类输入都将无限传递给异常块。因此你需要消耗这个值

} catch (InputMismatchException e) {
      System.err.println("Invalid integer: " + inputScanner.nextLine());
      ...
}

或者更好地使用hasNextInt

while (inputScanner.hasNextInt()) {
  ... // no boolean flag needed
}

【讨论】:

    【解决方案2】:
    } catch (InputMismatchException e) {
                correctInput = false;
                System.out.println("Please enter int value");
                inputScanner.next();
       }
    

    消耗一个令牌并继续

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      相关资源
      最近更新 更多