Ask Question
25 February, 07:11

rite a program that inserts parentheses, a space, and a dash into a string of 10 user-entered numbers to format it as a phone number. For example, 5153458912 becomes (515) 345-8912. If the user does not enter exactly 10 digits, display an error message. Continue to accept user input until the user enters 999. Save the file as PhoneNumberFormat. java.

+3
Answers (2)
  1. 25 February, 09:54
    0
    import java. util. Scanner;

    public class PhoneNumber

    {

    public static void main (String[] args) {

    Scanner input = new Scanner (System. in);

    while (true) {

    System. out. print ("Enter the phone number : ");

    String phoneNumber = input. nextLine ();

    if (phoneNumber. contains ("999"))

    break;

    if (phoneNumber. length () = = 10) {

    phoneNumber = phoneNumber. replaceFirst (" (//d{3}) (//d{3}) (//d+) ", " ($1) $2-$3");

    System. out. printf ("The formatted phone number is: %s / n", phoneNumber);

    }

    else

    System. out. println ("The phone number must be exactly 10 digits!");

    }

    }

    }

    Explanation:

    - Unless we specify a breaking condition inside the while loop, it will iterate

    - Ask the user for the phone number to be formatted

    - Check if the phone number is 999, if yes, stop the loop

    - If the phone number contains exactly 10 digits, format the phone number as requested using regex

    - Print the formatted phone number

    - If it has not 10 digits, print an error message
  2. 25 February, 11:02
    0
    Answer and Explanation:

    import java. util. Scanner;

    public class PhoneNumberFormat {

    public static void main (String args[]) {

    Scanner scanner = new Scanner (System. in);

    do {

    System. out. print ("/nEnter the Phone Number : ");

    String textPhone = scanner. nextLine ();

    if (textPhone. contains ("999"))

    break;

    if (textPhone. matches ("[0-9]+") && textPhone. length () = = 10) {

    System. out. println ("phoneNumber : " + " ("

    + textPhone. substring (0, 3) + ") "

    + textPhone. substring (3, 6) + "-"

    + textPhone. substring (6, 10));

    } else {

    System. out. println ("Error message!");

    }

    } while (true);

    scanner. close ();

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “rite a program that inserts parentheses, a space, and a dash into a string of 10 user-entered numbers to format it as a phone number. For ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers