java.util.Scanner can already check if the next token is of a given pattern/type with the hasNextXXX
methods.
Here's an example of using boolean hasNext(String pattern) to validate that the next token consists of only letters, using the regular expression [A-Za-z]+
:
Scanner sc = new Scanner(System.in);
System.out.println("Please enter letters:");
while (!sc.hasNext("[A-Za-z]+")) {
System.out.println("Nope, that's not it!");
sc.next();
}
String word = sc.next();
System.out.println("Thank you! Got " + word);
Here's an example session:
Please enter letters:
&#@#$
Nope, that's not it!
123
Nope, that's not it!
james bond
Thank you! Got james
To validate that the next token is a number that you can convert to int
, use hasNextInt() and then nextInt().
Related questions
- Validating input using java.util.Scanner - has many examples!