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.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.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerValidateLetter {
    public static void main(String[] args) {
        ScannerValidateLetter demo = new ScannerValidateLetter();
        demo.validateLetter();
    }

    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

13 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
  2. Could you explain why int number is used before the do while loop? (first example) I think it is to force the loop to run?

    Reply
    • Hi Michelle,

      We need to declare the variable because we will use it in the do-while statement. If we don’t declare it the do-while statement will not work as it will not find the variable in scope.

      Reply
  3. Wayan I want to thank you for your scanner validation code, I used it in a project for school, it’s only my second Java course so it really helped.

    Reply
  4. How to check the input values of a two by two array values only to be either 0 or 1 , where do I put the check validations here.
    Thank you.

    Reply
  5. Any chance examples could be more realistic rather than number? e.g. check for ENTER && check for multiple spaces in a row && check for !integer (if using string).

    Reply
  6. Hi, how do I do this? Write a program that reads a letter of the alphabet from the user. If the user enters a, e, i, o, or u, the program should display a message indicating that the entered letter is a vowel. Otherwise, it will display a message indicating that the letter is a consonant. Continue looping the program until the user chooses not to continue.

    Reply

Leave a Reply to Scott HamlinCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.