Skip to content

Instantly share code, notes, and snippets.

@TylerThompson
Created July 19, 2018 14:01
Show Gist options
  • Save TylerThompson/30fb64de142e495060a83e0c997806a3 to your computer and use it in GitHub Desktop.
Save TylerThompson/30fb64de142e495060a83e0c997806a3 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
/**
* Tyler Thompson
* Validate phone numbers
*/
public class phone {
private String pattern = "\\d{10}|(?:\\d{3}-){2}\\d{4}|\\(\\d{3}\\)\\d{3}-?\\d{4}";
public phone(){}
public String validate(String number){
return (number.matches(this.pattern)) ? "Valid" : "Invalid";
}
public String getPattern(){return this.pattern;}
public static void main(String[] args) {
String[] testStrings = {
/* Following are valid phone number examples */
"(123)4567890", "1234567890", "123-456-7890", "(123)456-7890",
/* Following are invalid phone numbers */
"(1234567890)","123)4567890", "12345678901", "(1)234567890",
"(123)-4567890", "1", "12-3456-7890", "123-4567", "Hello world"};
// current pattern recognizes any string of digits
// Apply regular expression to each test string
System.out.println("Running test suite");
for(String inputString : testStrings) {
phone p = new phone();
System.out.println(inputString + ": " + p.validate(inputString));
}
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter phone number");
String number = scanner.nextLine();
phone p = new phone();
System.out.println(number + ": " + p.validate(number));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment