Back scanner reading after user error - java

前端 未结 2 1863
轻奢々
轻奢々 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: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();
    

提交回复
热议问题