Back scanner reading after user error - java

前端 未结 2 1861
轻奢々
轻奢々 2021-01-16 16:25

I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to

2条回答
  •  爱一瞬间的悲伤
    2021-01-16 17:06

    A loop is the right idea. You just need to mark a success and carry on:

    boolean inputOK = false;
    while (!inputOK) {
        try{
            System.out.print("enter number: ");
    
            numAb = tastiera.nextInt();
    
            // we only reach this line if an exception was NOT thrown
            inputOK = true;
        } catch(InputMismatchException e) {
            // If tastiera.nextInt() throws an exception, we need to clean the buffer
            tastiera.nextLine(); 
        }
    }
    

提交回复
热议问题