CJ_Slip_9B

Slip No.9

B) Write a java program to validate PAN number and Mobile Number. If it is invalid then throw user defined Exception “Invalid Data”, otherwise display it.

1. Open Notepad.

2. Define the Custom Exception:

    class InvalidDataException extends Exception {
    public InvalidDataException(String message) {
    super(message);
    }
    }



3. Validation and Main Program:

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

    public class DataValidator {

    // Method to validate PAN number
    public static void validatePAN(String pan) throws InvalidDataException {
    // PAN number format: 5 letters, 4 digits, 1 letter
    if (!Pattern.matches("[A-Z]{5}[0-9]{4}[A-Z]{1}", pan)) {
    throw new InvalidDataException("Invalid PAN Number");
    }
    }

    // Method to validate Mobile number
    public static void validateMobile(String mobile) throws InvalidDataException {
    // Mobile number format: 10 digits starting with 7, 8, or 9
    if (!Pattern.matches("[789][0-9]{9}", mobile)) {
    throw new InvalidDataException("Invalid Mobile Number");
    }
    }

    public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    try {
    // Input PAN number
    System.out.print("Enter PAN number: ");
    String pan = scanner.nextLine();
    validatePAN(pan);

    // Input Mobile number
    System.out.print("Enter Mobile number: ");
    String mobile = scanner.nextLine();
    validateMobile(mobile);

    // If both are valid, display them
    System.out.println("PAN number: " + pan);
    System.out.println("Mobile number: " + mobile);

    } catch (InvalidDataException e) {
    System.out.println(e.getMessage());
    } finally {
    scanner.close();
    }
    }
    }



4. Open the Command Prompt.

5. Compile the Java program by typing:
javac DataValidator.java

6. Run the compiled Java program by typing:
java DataValidator

No comments:

Post a Comment