Continue a while loop after exception

前端 未结 6 494
春和景丽
春和景丽 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:07

    This works fine:

    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class Test {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int choice;
    
            while(true){
                try {
                    choice = input.nextInt();
                    System.out.println("Your choice: " + choice);
                } catch (InputMismatchException e){
                    e.printStackTrace();
                }
            }
        }
    }
    

提交回复
热议问题