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

假装没事ソ 提交于 2020-01-11 12:48:32

问题


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

回答1:


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



回答2:


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



回答3:


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!




回答4:


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


来源:https://stackoverflow.com/questions/26684729/reading-input-using-scanner-causes-an-infinite-loop-in-java

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