java - 来自扫描仪的 hasNextInt() 行为异常

标签 java user-input java.util.scanner

我有一个等待数字 (int) 的非常简单的循环,只要该数字不是 exitOption 它就不会离开循环,但是我得到了一个意外错误,我没有不知道是什么原因造成的。

编辑

添加另一个片段以便您可以编译

public static void main(String[] args) throws   FileNotFoundException,
                                                SecurityException,
                                                IOException,
                                                ClassNotFoundException {


    while (controller.selectOptionMM());

/编辑

public boolean selectOptionMM() throws  SecurityException, 
                                        FileNotFoundException, 
                                        IOException {

    int cmd = ui.getExitOption();

    ui.mainMenu();
    cmd = utils.readInteger(">>> "); // this is my problem, right here
                                     // code in next snippet 
    while (cmd <1 || cmd > ui.getExitOption()) {
        System.out.println("Invalid command!");
        cmd = utils.readInteger(">>> ");
    }

    switch (cmd) {
    case 1: 
    case 2: 
    case 3: 
    case 4: this.repository.close();
            return true;
    case 5: return false;
    }

    return false;
}

这里是失败的地方:

public int readInteger(String cmdPrompt) {
    int cmd = 0;
    Scanner input = new Scanner(System.in);

    System.out.printf(cmdPrompt);
    try {
        if (input.hasNextInt()) 
            cmd = input.nextInt(); // first time it works
            // Second time it does not allow me to input anything
                            // catches InputMissmatchException, does not print message
                            // for said catch
                            // infinitely prints "Invalid command" from previous snippet

    } catch (InputMismatchException ime) {
        System.out.println("InputMismatchException: " + ime);
    } catch (NoSuchElementException nsee) {
        System.out.println("NoSuchElementException: " + nsee);
    } catch (IllegalStateException ise) {

    } finally {
        input.close(); // not sure if I should test with if (input != null) THEN close
    }


    return cmd;
}

第一次 我通过了槽,它读取数字没问题。现在,如果数字不是 5(在本例中为 exitOption),它会再次通过 readInteger(String cmdPrompt),除了这次它会跳转到 catch (InputMismatchException ime)(调试) 除了它不打印该消息而只是跳转到 Error, input must be numberInvalid command

我的输入缓冲区中是否有东西卡住了,我可以刷新它吗,为什么它(输入缓冲区)卡住了(带有随机数据)???

我会再次尝试调试,看看我的输入缓冲区中卡住了什么,如果我能弄清楚如何查看的话。

最佳答案

问题出在对 input.close() 的调用中 - 这会导致关闭基础输入流。当被关闭的输入流是 System.in 时,就会发生不好的事情(即,您无法再从标准输入读取数据)。删除这一行应该没问题。

关于java - 来自扫描仪的 hasNextInt() 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14060165/

相关文章:

c++ - 如何将数据输入数组并通过函数打印出来?

JavaScript 变量和用户输入

java - 如何使用正则表达式从字符串中删除外部标点符号

java - 在 Android 上使用超链接 API 的最佳方式是什么?

java - 在 Jenkins 管道中使用 Sonarqube 分析 Gradle Java 项目会在 Jacoco 报告上引发异常

Java反射;如何使用 Method.invoke() 检索对象数组?

java - 将整数作为控制台的输入并将它们存储在数组中

java - 如何从数据库(MySQL)中分块获取记录

java - 错误用户输入Java的异常处理

java - Java 温度计算器