使用 Scanner 读取输入会导致 Java 中的无限循环 [英] Reading input using Scanner causes an infinite loop in Java

查看:37
本文介绍了使用 Scanner 读取输入会导致 Java 中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我试图让用户输入一个 1-3 之间的整数,然后根据他们输入的内容做一些事情.如果它不是数字或不是选项之一,则允许他们重新输入有效选项.

In my program I'm trying to get a user to input an int between 1-3 and then do something based off what they type. If it is not a number or not one of the options then it will allow them to reenter a valid option.

我遇到的问题是我无法集思广益,如何不让它无限循环,只允许他们在控制台告诉他们输入无效输入后输入一个数字.

The issue I have is I'm having trouble brainstorming how to not have it infinitely loop and just allow them to enter in a number after the console tells them they entered an invalid input.

int i = 0;
while (i < 1) {
    try {
        int level = scan.nextInt();
        i+=1;
        if (level == 1) {
            System.out.println("You selected level 1!");
            //Start the game
        } else if (level == 2) {
            System.out.println("You selected level 2!");
            //Start the game
        } else if (level == 3) {
            System.out.println("You selected level 3!");
            //Start the game
        } else {
            System.out.println("That's not an option!");
            i-=1;
        }
    } catch(InputMismatchException input) {
        System.out.println("That's not an option!");
        i-=1;
    }
}

推荐答案

当您输入无效的输入时,您需要将其清除.触发输入异常时添加scan.next(),以便用next():

When you input an invalid input, you need to clear it. Add scan.next() when input exception triggered so as to clear it with next():

 catch(InputMismatchException input) {
        System.out.println("That's not an option!");
        scan.next();
        i-=1;
    }

这篇关于使用 Scanner 读取输入会导致 Java 中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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