How do I validate input when using Scanner?

This example show you how to validate input when using java.util.Scanner. To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

In the code snippet below will demonstrate how to validate whether the user provide a positive integer number. The program will repeat until the correct input is supplied.

package org.kodejava.example.util;

import java.util.Scanner;

public class ScannerValidateInput {
    public static void main(String[] args) {
        ScannerValidateInput demo = new ScannerValidateInput();

    private void validatePositiveNumber() {
        Scanner scanner = new Scanner(;

        int number;
        do {
            System.out.print("Please enter a positive number: ");
            while (!scanner.hasNextInt()) {
                String input =;
                System.out.printf("\"%s\" is not a valid number.\n", input);
            number = scanner.nextInt();
        } while (number < 0);

        System.out.printf("You have entered a positive number %d.\n", number);

The output produce by the snippet:

Please enter a positive number: qwerty
"qwerty" is not a valid number.
"@@@" is not a valid number.
Please enter a positive number: 99
You have entered a positive number 99.


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.


Leave a Reply