Phone Number And Zip Code Validation Using Java Regular Expressions And User Defined Exception Java Source Code

Phone Number And Zip Code Validation Using Java Regular Expressions And User Defined Exception Java Source Code

The following code verifies zip codes and phone number format using regular expressions and user defined exceptions. Code in the main class loops until user enters data that matches specific regular expression.

SOURCE CODE

PhoneNumberException.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package serviceprovidercustomerpkgpackagedefinedexceptionphonenumberzipcoderegex;

/**
 *
 * @author HP
 */
// custome exception class to handle invalid phone numbers
// this class extends the Exception class and calls its constructor with a message
class PhoneNumberException extends Exception {

    public PhoneNumberException(String msg) {
        super(msg);
    }
}

ZipCodeException.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package serviceprovidercustomerpkgpackagedefinedexceptionphonenumberzipcoderegex;

/**
 *
 * @author HP
 */
// custome exception class to handle invalid zipcodes
// this class extends the Exception class and calls its constructor with a message
class ZipCodeException extends Exception {

    public ZipCodeException(String msg) {
        super(msg);
    }
}


Person.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package serviceprovidercustomerpkgpackagedefinedexceptionphonenumberzipcoderegex;

import java.util.Scanner;
import java.util.regex.Pattern;

/**
 *
 * @author HP
 */
// class representing a person
class Person {

    String zip, phone;
    Scanner input;

    public Person() // default constructor
    {
        input = new Scanner(System.in);
    }

// method to accept and validate phone number entered by user
    void getPhoneNumber() {
        boolean invalid;

// loop until user enteres a valid phone number
        do {
// ask for a phone number
            System.out.println("Enter Phone Number :");
            phone = input.nextLine();

// match the given number with regular exp.
            try {
                if (Pattern.matches("^\\(\\d{3}\\)\\s\\d{3}-\\d{4}", phone)) {
                    invalid = false;
                } else // if dosen't matches, then throw new exception
                {
                    throw new PhoneNumberException("Sorry Enter Correct Phone Number");
                }
            } catch (PhoneNumberException p) // catch the exception
            {
                System.out.println(p.getMessage());
                invalid = true;
            }

        } while (invalid);
    }

// method to accept and validate zip code entered by user
    void getZipCode() {
        boolean invalid;

// loop until user enteres a valid phone number
        do {
// ask for a zip code
            System.out.println("Enter Zip : ");
            zip = input.nextLine();

// match the given zip code with regular exp. of zip code
            try {
                if (Pattern.matches("[\\d]{5}", zip)) {
                    invalid = false;
                } else // if dosen't matches, then throw new exception
                {
                    throw new ZipCodeException("Sorry Enter Correct Zip");
                }
            } catch (ZipCodeException p) // catch the exception
            {
                System.out.println(p.getMessage()); // print appropriate message
                invalid = true;
            }

        } while (invalid);

    }
}


ServiceProviderCustomerPackageDefinedExceptionPhoneNumberZipCodeRegexDriver.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package serviceprovidercustomerpkgpackagedefinedexceptionphonenumberzipcoderegex;

import java.util.Scanner;

/**
 *
 * @author HP
 */
public class ServiceProviderCustomerPackageDefinedExceptionPhoneNumberZipCodeRegexDriver {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        int choice;
        Scanner input = new Scanner(System.in);
        Person person = new Person(); // Person class's object

// loop until user wants to exit
        while (true) {
// print the menu
            System.out.println("Menu\n"
                    + "1. Enter Phone Number\n"
                    + "2. Enter Zip\n"
                    + "3. Exit\n"
                    + "Enter your Option : ");
            choice = input.nextInt();

// compare the user given choice with different options
// and take actions accordingly
            switch (choice) {
                case 1:
                    person.getPhoneNumber();
                    break;
                case 2:
                    person.getZipCode();
                    break;
                case 3:
                    System.exit(0);
                default:
                    System.out.println("Invalid option !!, try again");
            }
        }
    }

}


OUTPUT

run:
Menu
1. Enter Phone Number
2. Enter Zip
3. Exit
Enter your Option : 
1
Enter Phone Number :
123456789
Sorry Enter Correct Phone Number
Enter Phone Number :
(123) 456-7890
Menu
1. Enter Phone Number
2. Enter Zip
3. Exit
Enter your Option : 
2
Enter Zip : 
1234
Sorry Enter Correct Zip
Enter Zip : 
12345
Menu
1. Enter Phone Number
2. Enter Zip
3. Exit
Enter your Option : 
1
Enter Phone Number :
123) 456-6789
Sorry Enter Correct Phone Number
Enter Phone Number :
123 456-7890
Sorry Enter Correct Phone Number
Enter Phone Number :
(123) 456-7890
Menu
1. Enter Phone Number
2. Enter Zip
3. Exit
Enter your Option : 
3
BUILD SUCCESSFUL (total time: 3 minutes 39 seconds)

READ MORE  How To Update Windows 10 To Latest Version

Leave a Reply

Your email address will not be published. Required fields are marked *