Java:使用 Scanner in.hasNextInt() 的无限循环 [英] Java: Infinite loop using Scanner in.hasNextInt()

查看:40
本文介绍了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 之间的整数:您输入的输入无效.再试一次."

However, if I enter a 'w' it will tell me "You have entered invalid input. Try Again." and then it will go into an infinite loop showing the text "Specify an integer between 0 and 5: You have entered an invalid input. Try again."

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

Why is this happening? Isn't the program supposed to wait for the user to input and press enter each time it reaches the statement:

if (in.hasNextInt())

推荐答案

在最后一个 else 块中,您需要从 Scanner 清除 'w' 或其他无效输入.您可以通过在 Scanner 上调用 next() 并忽略其返回值以丢弃无效输入来完成此操作,如下所示:

In your last else block, you need to clear the 'w' or other invalid input from the Scanner. You can do this by calling next() on the Scanner and ignoring its return value to throw away that invalid input, as follows:

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

这篇关于Java:使用 Scanner in.hasNextInt() 的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆