X1634: Convert phone number

Write the method String convertPhone(String number) in Java that implements the following logic: Given a phone number as a string of digits return a properly formatted phone with the area code surrounded by parenthesis, followed by a space, the exchange (next 3 digits), a hyphen, and the remaining four digits.

The parameter number is either

  • a 7 digit number, in which case it doesn't have an area code and you have to insert "704" in front, or
  • a 10 digit number with includes area code (first 3 digits), exchange number (next 3) and the last four digits (sometimes referred to as the subscriber number).

The result should always be of the format "(xxx) yyy-zzzz" with the letters replaced by the appropriate number.

You may consult the Java String class documentation to help you solve this problem.

Examples:

convertPhone("8885882300") -> "(888) 588-2300"
convertPhone("2342299") -> "(704) 234-2299"

Your Answer:

Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.