加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 07:38:18 所属栏目:Java 来源:网络整理
导读:我使用以下代码: 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
我使用以下代码:

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之间的整数:您输入的输入无效.请再试一次.”

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

if (in.hasNextInt())

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读