How to loop user input until an integer is inputted?

Take the input using next instead of nextInt. Put a try catch to parse the input using parseInt method. If parsing is successful break the while loop, otherwise continue.
Try this:

        System.out.print("input");
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("Enter a whole number.");
            String input = sc.next();
            int intInputValue = 0;
            try {
                intInputValue = Integer.parseInt(input);
                System.out.println("Correct input, exit");
                break;
            } catch (NumberFormatException ne) {
                System.out.println("Input is not a number, continue");
            }
        }

Leave a Comment