0

How can I make it so input from the user will only be accepted if the format is exactly "xxx-xxx-xxxx" where x can be any number, but only numbers, and the dashes have to be there, in those groupings. Basically, it's supposed to accept phone numbers. Right now I have:

Scanner input = new Scanner(System.in);
String in = input.next(); // Stores user input as a string

if (in.contains("[a-zA-Z]") == false && in.length() == 12) {
    System.out.println("Number Accepted");
} else {
    System.out.println("Number Rejected");
}

Currently, it will reject numbers that are greater or less than 12 characters, but it will accept anything that is 12 characters, even if it has letters. I also do not a solution to grouping the numbers with the dashes correctly, as the user should only be able to input 3 numbers, then a dash, then 3 more numbers, then a dash, and then finally 4 numbers.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132

1 Answers1

1

You could use a Pattern to apply a regular expression:

Pattern pattern = Pattern.compile("^\d{3}-\d{3}-\d{4}$");
Scanner input = new Scanner(System.in);
String in = input.next(); // Stores user input as a string

if (pattern.matcher(in).matches())) {
    System.out.println("Number Accepted");
} else {
    System.out.println("Number Rejected");
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350