Write 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:

import java.util.Scanner; // package import

public class Main // main class

{

   public void phone() //function definition

   {

      Scanner ob = new Scanner(System.in);// scanner class

      String phno = " ";

     System.out.println("Enter 10-digit of Us telephone number: ");

      phno = ob.next();

      if(phno.length() != 10) // checking the length of phone number

      {

          System.out.println("Enter a valid 10-digit number..."); // print error message

      }

      else

      {

          System.out.println("The phone number you entered: "+phno);

          String a = phno .substring(0,3); // calculate the area code

          String exh = phno.substring(3,6);//calculate the exchange code

          String num1 = phno.substring(6,10);//calculate the phone number

          System.out.println("Area code is :"+a);// display area code

          System.out.println("Exchange is: "+exh);// display exchange code

          System.out.println("Number is: "+num1);//display  phone number

          System.out.println("The complete telephone number : ("+a+") "+exh+"-"+num1);// DISPLAY COMPPLETE NUMBER

      }

   }

public static void main(String[] args) // MAIN METHOD

{

Main ob =new Main(); // CREATING an object of class Main

ob.phone();// calling function phone method

}

}

Explanation:

In the given program we create a function phone of void return type  and input a phone number in "phno " variable by using scanner class object After that check the length of phone number by using length() method if length is 10 then we extracts the area code ,exchange code and  remaining number by using substring method which is used to extract the character from string and finally display the complete telephone number in proper formatting. If length does not equal to 10 it print error message .

Output:

Enter 10-digit of Us telephone number:1234567890

The phone number you entered:1234567890

Area code is :123

Exchange is:456

Number is:7890

The complete telephone number : (123) 456-7890

ACCESS MORE