Continue a while loop after exception

前端 未结 6 526
春和景丽
春和景丽 2021-01-16 12:39

i have this piece of code. I wanted to return to the beginning of loop and ask for user input again. However, it always loops without stopping to ask for input. What is wron

6条回答
  •  春和景丽
    2021-01-16 13:01

    From http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28int%29 :

    "If the translation is successful, the scanner advances past the input that matched."

    Ah, but what if the translation is not successful? In that case, the scanner does not advance past any input. The bad input data remains as the next thing to be scanned, so the next iteration of the loop will fail just like the previous one--the loop will keep trying to read the same bad input over and over.

    To prevent an infinite loop, you have to advance past the bad data so that you can get to something the scanner can read as an integer. The code snippet below does this by calling input.next():

        Scanner input = new Scanner(System.in);
        while(true){
            try {
                int choice = input.nextInt();
                System.out.println("Input was " + choice);
            } catch (InputMismatchException e){
                String bad_input = input.next();
                System.out.println("Bad input: " + bad_input);
                continue;
            }
        }
    

提交回复
热议问题