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();
        demo.validatePositiveNumber();
    }

    private void validatePositiveNumber() {
        Scanner scanner = new Scanner(System.in);

        int number;
        do {
            System.out.print("Please enter a positive number: ");
            while (!scanner.hasNextInt()) {
                String input = scanner.next();
                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.
-100
Please enter a positive number: 99
You have entered a positive number 99.

Another example is to validate if user correctly input letters to guest a secret word. In the code snippet below if the user does not enter a letter the code will keep asking for a valid letter. It loops until the length of the inputted letters equals to the length of secret word.

private void validateLetter() {
    String secretWord = "Hello";
    Scanner scanner = new Scanner(System.in);

    int length = 0;
    StringBuilder guess = new StringBuilder();
    do {
        System.out.print("Enter a letter to guess: ");
        char letter = scanner.next().charAt(0);
        if (Character.isLetter(letter)) {
            guess.append(letter);
            length++;
        }
    } while (length < secretWord.length());

    if (secretWord.equalsIgnoreCase(guess.toString())) {
        System.out.println("You are correct!");
    } else {
        System.out.println("Please try again!");
    }
}
Enter a letter to guess: 1
Enter a letter to guess: 2
Enter a letter to guess: H
Enter a letter to guess: e
Enter a letter to guess: l
Enter a letter to guess: l
Enter a letter to guess: o
You are correct!

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me, buy me ☕ or 🍵

4 Comments

  1. How about testing for a valid char? I need to validate a 1-letter guess for a hangman game.

    I want to prompt the user:

    Enter a letter to guess: 
    

    And I want to repeat this prompt until they enter a valid letter, meaning if they enter anything that is NOT a letter (including entering nothing) I want to repeat the prompt.

    Reply

Leave a Reply