使用Scanner读取输入会导致Java中出现无限循环

使用Scanner读取输入会导致Java中出现无限循环

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

问题描述

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

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(),以便用:

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中出现无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:42