Back scanner reading after user error - java

前端 未结 2 1854
轻奢々
轻奢々 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(); 
        }
    }
    
    0 讨论(0)
  • 2021-01-16 17:09

    While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.

    System.out.print("enter number: ");
    while (!scanner.hasNextInt()) {
        scanner.nextLine();// consume incorrect values from entire line
        //or 
        //tastiera.next(); //consume only one invalid token
        System.out.print("enter number!: ");
    }
    // here we are sure that user passed integer
    int value = scanner.nextInt();
    
    0 讨论(0)
提交回复
热议问题