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!
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
So how can I get the input to display on the same line as the println?
Hi,
You can use
System.out.print()
instead ofSystem.out.println()
. This will make the input on the same line with the label.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:
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.
Hi Phil,
To check if a character is a letter / alphabet you can use the
java.lang.Character.isLetter(char ch)
method.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?
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.
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.
Hi Scott, you’re welcome 🙂
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.
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).
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.