204k views
5 votes
Write a program called telephone.java that prompts the user to enter their phone number using the specific format: (xxx) xxx-xxxx. The program should check whether the input entered is valid. The program must also check for the parenthesis () for the area code (the first three numbers). Example: (702)892-0516 would be correct but 702-892-0516 would not be correct. Example: Enter your phone number: 702-908-1333. 702-908-1333 is a NOT a valid phone number as there are no parenthesis (). Another example: Enter your phone number: (70 –290-8133 (70—290-8133 is NOT a valid phone number. If the entered telephone number is valid the program should return a statement that says the phone number is valid.

User Virtualmic
by
5.1k points

1 Answer

4 votes

Answer:

Following are the program in the Java Programming Language.

//import package scanner class

import java.util.Scanner;

//define class

public class telephone {

//define main method

public static void main(String[] args) {

//set object of the scanner class

Scanner sc = new Scanner(System.in);

//print message

System.out.println("Enter tele-phone no. using this format: (xxx)xxx-xxxx: ");

//get input from the user

String phn = sc.next();

//check length of phone number is equal to 13

if(phn.length() == 13) {

//check phone no. containing parentheses

if(phn.charAt(0) == '(' && phn.charAt(4)==')' && phn.charAt(8) == '-') {

//initializing the values

String num1 = phn.substring(1,4);

String num2 = phn.substring(5,8);

String num3 = phn.substring(9);

//check the following input is numeric or not

if(num1.matches("[0-9]+") && num2.matches("[0-9]+")&& num3.matches("[0-9]+")) {

//then, print valid message

System.out.println("Given phone number is valid");

}

//otherwise

else {

//print invalid message

System.out.println("Given phone number is invalid");

}

}

//otherwise

else {

//print invalid message

System.out.println("Given phone number is invalid");

}

}

//otherwise

else {

//print invalid message

System.out.println("Given phone number is invalid");

}

}

}

Step-by-step explanation:

Following are the desciption of the program

  • Declared a class telephone
  • Read a input phone number in phn variable of string type.

Check the following condition of phone number

  • if "phn"=="13" then it check for the parenthesis and number is valid otherwise phn number is invalid .
User Calista
by
5.2k points