PhoneNumber.java 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package com.zipcodewilmington.phone;
  2. import com.zipcodewilmington.exceptions.InvalidPhoneNumberFormatException;
  3. /**
  4. * Created by leon on 5/10/17.
  5. */
  6. public final class PhoneNumber {
  7. private final String phoneNumberString;
  8. // default constructor is uncallable
  9. private PhoneNumber() throws InvalidPhoneNumberFormatException {
  10. this(null);
  11. }
  12. // non-default constructor is package-protected
  13. protected PhoneNumber(String phoneNumber) throws InvalidPhoneNumberFormatException {
  14. //validate phone number with format `(###)-###-####`
  15. if (!phoneNumber.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) {
  16. throw new InvalidPhoneNumberFormatException();
  17. }
  18. this.phoneNumberString = phoneNumber;
  19. }
  20. public String getAreaCode() {
  21. return toString().substring(1, 4);
  22. }
  23. public String getCentralOfficeCode() {
  24. return toString().substring(6, 9);
  25. }
  26. public String getPhoneLineCode() {
  27. return toString().substring(10, 14);
  28. }
  29. @Override
  30. public String toString() {
  31. return phoneNumberString;
  32. }
  33. }