Beginners Programs :

Java: Validating a Phone Number Format String | Java Programs

Java program to validate the phone number format in a perfect order with dashes. The following java program has written in multiple ways along with detailed algorithmic explanation with sample outputs. If you have any doubts related to the Java phone number format, just do leave a comment here.

Consider you entered the mobile number like 9 0 1 0 4 8 6 2 7 5, and it will convert more likely to be (+91) 9010-486275

Java Code For Phone Number Format

Here is the Java program for phone number/Mobile number validation, check detailed explanation after the output:

Output:

 

Code Explanation:

To solve the problem, we first need a thorough understanding of the problem statement and see if there are any constraints given in the problem statement.

After this, we need to determine the inputs required to solve the problem along with the expected output of the problem.

Then, we decide on the steps to be taken in to reach this expected output.

In this, our problem statement is to display the given input in the phone number format. For this, our required input would be an array of size 10 denoting the 10-digit phone number.

Our expected output is the phone number format by splitting into area code and local number.

Our first step is, to read the value of individual digit and store it in the array. This value can be read at runtime using the Scanner class in Java.

This is a very common system input class consisting of several methods to read any primitive datatype input at runtime. Since, each of our digit is an integer only, we will make use of nextInt() method by creating an object of Scanner class first as follows:

As we read individual input, we simultaneously check whether the input is less than zero or greater than 9 and stop the execution if that is the case.

This is done because, if it isn’t between 0-9 both inclusive, it is an invalid digit for a phone number.

Now that our required input is gathered, we have to display it in phone number format. The first three digits of the phone number indicates the area code, then next seven numbers are split into two parts with three in a group and four in another.

For this, from first to third digit, we are going to enclose in a parenthesis and after sixth digit we will place a hyphen (-) symbol indicating the separation of the digits while displaying in the console screen. All the digits of array are printed normally. This can be done as below:

So, at zeroth index we open the parenthesis before printing the digit. At index 3, we close the parenthesis before printing the digit. At index 6, we place a hyphen before printing the digit. This represents the phone number format of 10-digits.