I am asking the user to enter his/her name. What can I do so that numbers won't be excepted?
String name = " ";
System.out.println("Enter Name");
name = Keyboard.readString();
I am asking the user to enter his/her name. What can I do so that numbers won't be excepted?
String name = " ";
System.out.println("Enter Name");
name = Keyboard.readString();
Use regex to check the input and a loop to get a good answer:
String name = "";
while (true) {
System.out.println("Enter Name");
name = Keyboard.readString();
if (name.matches("[a-zA-Z]+"))
break;
System.out.println("Invalid input. Enter letters only");
}
boolean numberOrNot = name.matches(".*\\d.*");
numberOrNot
will be true
if it name has any number, else it will be false
.
regex means, Regular Expressions.
-?\\d+
is a regex.
-?
: negative sign, could have none or one\\d+
: one or more digitsBut this is validation, I don't think you can put limitation on console.
You cant make user put only characters in console and nothing else while typing, but you can validate his input and check if it contains only alphabetic characters after he put it and in case of invalid one ask user to type his data again.
To check if String contains only alphabetic characters you can iterate over all its characters and use Character.isAlphabetic(character)
on them or just use matches
with regex like this one userData.matches("\\p{IsAlphabetic}+");
Character.isAlphabetic
and \\p{IsAlphabetic}
has advantage over checking a-zA-Z
range because it will also accept non English characters like ą
, ę
.