Ask Question
11 October, 18:19

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.

+1
Answers (2)
  1. 11 October, 18:26
    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. 11 October, 19:37
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers