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

查看:283
本文介绍了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 阻止,您需要清除扫描仪中的w或其他无效输入。您可以通过在扫描程序上调用 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天全站免登陆