The complete telephoneWrite a Java program that asks the user to enter a 10-digit string as a typical U.S. telephone number, extracts the 3-digit area code, the 3-digit "exchange," and the remaining 4-digit number as separate strings, prints them, and then prints the complete telephone number in the usual formatting with parentheses. If the user does not enter a 10-digit number, print an error message.

Respuesta :

Answer:

Here is code in java.

//import package

import java.util.*;

//class definition

public class Main

{

   //main method off the class

public static void main(String[] args)

{

    // Scanner class Object to read the input

 Scanner obj = new Scanner(System.in);

 String phone_num;

 System.out.println("Please enter the 10 digit phone number:");

 //read phone number

 phone_num=obj.next();

 //validate the input number

 while(true)

 {

     /* if the length of phone number is less than 10 then it will again ask to enter the phone number*/

     if(phone_num.length() != 10)

         System.out.println("Wrong input !!!Enter a 10 digit phone number only:");

     else

           break;

           System.out.print("\nEnter the number again: ");

           phone_num = obj.next();

 }

 //extract the area code

   String area_code = phone_num.substring(0,3);

   //extract the Exchange code

   String ex_code = phone_num.substring(3,6);

           //remaining number

          String rem_num = phone_num.substring(6,10);

          // print the output

           System.out.println("Area code in the phone number is :"+area_code);

           System.out.println("Exchange code in the phone number is:"+ex_code);

           System.out.println("remaining number is:"+rem_num);

  System.out.println("The complete phone number in the format is: ("+area_code+") "+ex_code+"-"+rem_num);

}

}

Explanation:

Use scanner class object to read phone number from user.If the length of the phone number is not equal to 10 then it will print an error message and ask user to enter a valid phone number.After the valid input it will extracts the first 3-digit as area code, next 3-digits as Exchange code and rest 4 digit as number.Then print the phone number in the usual format.

Output:

Please enter the 10 digit phone number:

136787628

Wrong input !!!Enter a 10 digit phone number only:

Enter the number again: 1234098765

Area code in the phone number is :123

Exchange code in the phone number is:409

remaining number is:8765

The complete phone number in the format is: (123) 409-8765

ACCESS MORE