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

时间:2014-10-31 23:13:43

标签: java while-loop infinite-loop ioexception

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

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

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;
    }
}

4 个答案:

答案 0 :(得分:2)

输入无效输入时,需要清除它。触发输入异常时添加scan.next(),以便使用next()清除它:

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

答案 1 :(得分:0)

不是你期望的答案,但是:重构这段代码。记住java的基础知识,其中每个功能位都有自己的方法。因此,使用一个读取输入的方法,并返回所选的级别(如果没有则返回-1):

int readInput() {
  // your code here, returning either the level or -1 on bad input
}

然后将其称为读取循环:

int selected;
do {
  selected = readInput();
} while(selected < 1);

答案 2 :(得分:0)

你最好写这样的代码:

while(true){
    try{
        int level = scan.nextInt();
        if(level==1){
            System.out.println("You selected level 1!");
            break;
        }else if(level==2){
            System.out.println("You selected level 2!");
            break;
        }else if(level==3){
            System.out.println("You selected level 3!");
            break;
        }else{
            System.out.println("That's not an option!");
            continue;
        }
    }catch(InputMismatchException input){
        System.out.println("That's not an option!");
        continue;
    }
}

continue将立即在顶部继续执行循环,break将立即跳过while的右括号}。这消除了使用i计数器变量,这对代码完全没用。此外,此代码永远不会无限期运行,除非用户无限期输入不正确的值!

希望这有所帮助,祝你好运!

答案 3 :(得分:0)

您可以采用更简单的方式进行操作。 3个有效案例非常相似,可以视为一个,游戏只能在循环后启动一次,因为我们知道一旦循环退出,level有一个有效值。

boolean valid = false;
int level;
do  {
    try {
        level = scan.nextInt();
        valid = 1 <= level && level <= 3;

        if (valid) {
            System.out.println(String.format("You selected level %d !",level));    
        } else {
            System.out.println("That's not an option!");
        }
    } catch(InputMismatchException input) {
        scan.next();
        System.out.println("That's not an option!");
    }
} while (!valid);

// start the game