Java:无限循环使用 Scanner in.hasNextInt()

新手上路,请多包涵

我正在使用以下代码:

 while (invalidInput)
{
    // ask the user to specify a number to update the times by
    System.out.print("Specify an integer between 0 and 5: ");

    if (in.hasNextInt())
    {
        // get the update value
        updateValue = in.nextInt();

        // check to see if it was within range
        if (updateValue >= 0 && updateValue <= 5)
        {
            invalidInput = false;
        }
        else
        {
            System.out.println("You have not entered a number between 0 and 5. Try again.");
        }
    } else
    {
        System.out.println("You have entered an invalid input. Try again.");
    }
}

但是,如果我输入“w”,它会告诉我“您输入的内容无效。请重试。”然后它将进入一个无限循环,显示文本“请指定一个介于 0 和 5 之间的整数:您输入的内容无效。请重试。”

为什么会这样?程序不是应该在每次到达语句时等待用户输入并按回车键吗:

 if (in.hasNextInt())

原文由 Tomek 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

在您的最后一个 else 块中,您需要清除扫描程序中的“w”或其他无效输入。您可以通过在 Scanner 上调用 next() 并忽略其返回值以丢弃无效输入来执行此操作,如下所示:

 else
{
      System.out.println("You have entered an invalid input. Try again.");
      in.next();
}

原文由 Kaleb Brasee 发布,翻译遵循 CC BY-SA 2.5 许可协议

问题是您没有将 Scanner 推进到有问题的输入之后。来自 hasNextInt() 文档:

返回 true 如果此扫描器输入中的下一个标记可以解释为 int 使用 nextInt() 方法的默认基数中的值。 扫描仪不会前进超过任何输入。

This is true of all hasNextXXX() methods: they return true or false , without advancing the Scanner .

这里有一个片段来说明这个问题:

     String input = "1 2 3 oops 4 5 6";
    Scanner sc = new Scanner(input);
    while (sc.hasNext()) {
        if (sc.hasNextInt()) {
            int num = sc.nextInt();
            System.out.println("Got " + num);
        } else {
            System.out.println("int, please!");
            //sc.next(); // uncomment to fix!
        }
    }

你会发现这个程序会进入死循环,反复询问 int, please!

如果您取消注释 sc.next() 语句,那么它将使 Scanner 越过失败的标记 hasNextInt() 然后程序会打印:

 Got 1
Got 2
Got 3
int, please!
Got 4
Got 5
Got 6

事实上,失败的 hasNextXXX() 检查不会跳过输入是有意的:它允许您在必要时对该令牌执行额外的检查。下面举个例子来说明:

     String input = " 1 true foo 2 false bar 3 ";
    Scanner sc = new Scanner(input);
    while (sc.hasNext()) {
        if (sc.hasNextInt()) {
            System.out.println("(int) " + sc.nextInt());
        } else if (sc.hasNextBoolean()) {
            System.out.println("(boolean) " + sc.nextBoolean());
        } else {
            System.out.println(sc.next());
        }
    }

如果你运行这个程序,它会输出以下内容:

 (int) 1
(boolean) true
foo
(int) 2
(boolean) false
bar
(int) 3

原文由 polygenelubricants 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题