Reading input using Scanner causes an infinite loop in Java [duplicate]

与世无争的帅哥 提交于 2019-12-02 08:45:59

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

Not quite the answer you were expecting, but: refactor this code. Remember the basics of java, where every functional bit has its own method. So use a method that reads the input, and returns the level selected (or -1 if nothing):

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

And then call that for your read loop:

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

You are better off writing the code like this:

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 will immediately resume execution of the loop at the top, and break will immediately jump too the closing brace } of the while. This removes the use of the i counter variable, which was entirely useless to the code. Also, this code will never run indefinitely, unless the user indefinitely enters improper values!

Hope this helped, good luck!

You can proceed in a much simpler way. The 3 valid cases are very similar and can be treated as one, the game can be started only once after the loop because we know that once the loop exits, level has a valid value.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!