2

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();
An SO User
  • 24,612
  • 35
  • 133
  • 221
Kurt Camilleri
  • 133
  • 1
  • 1
  • 11

3 Answers3

4

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");
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Does `matches` require the whole string to match? If not you'll need to anchor it (`^` and `$`) – Kevin Oct 20 '13 at 15:47
  • @Kevin yes. ^ and $ are implied with java's matches(), unlike JavaScript, perl, ruby etc – Bohemian Oct 20 '13 at 15:49
  • What poor design. Though not the first for Java. – Kevin Oct 20 '13 at 15:58
  • @kevin I agree :( if there's a defacto standard, unless you've got a good reason not to, just use it. See [this answer](http://stackoverflow.com/questions/7281469/why-is-java-util-observable-not-an-abstract-class/7284322#7284322) for a few more design errors in java – Bohemian Oct 20 '13 at 21:04
0
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 digits

But this is validation, I don't think you can put limitation on console.

codingenious
  • 8,385
  • 12
  • 60
  • 90
0

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 ą, ę.

Pshemo
  • 122,468
  • 25
  • 185
  • 269