Skip to main content

Command Palette

Search for a command to run...

PGDAC | OOP Java | Assignment

- Module taught by Madhura Anturkar

Updated
•9 min read•View as Markdown
PGDAC | OOP Java | Assignment
A

Learning Fullstack Development using Java and .Net Aspiring Public Speaker Cofounder @BookBrotherhood Part-time Musician🎶 and Writer✒️ Live😊 | Love❤️ | Laugh😁


Customer Assignment:

Problem Statement:

Create a Java Application for Customer Management System:
The application should allow the user to:
1. SignUp
2. SignIn
3. Change Password
4. Unscubsrice
5. Display all Existing Users

Customer HAS-A
customer id(int),
first name (String),
last name (String),
email (String),
password (String),
registration amount(double),
dob(LocalDate),
plan(ServicePlan : enum)

ServicePlan charges:
SILVER: 1000
GOLD: 2000
DIAMOND: 5000
PLATINUM: 10000

Depending on the plan chosen, the Customer will have to pay the specific registration amount

Customer id should be system-generated, using auto-increment functionality.

Unique ID(Primary Key ):
Email (2 customers are SAME if their email ids are the same)


Solution:

Here is the source code of all the classes made for the solution of the Problem

// Customer Class

import java.time.LocalDate;

public class Customer {
    private int id;
    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private double registrationAmount;
    private LocalDate dob;
    private ServicePlan plan;

    private static int id_counter;

    static {
        id_counter = 233000;
    }

    // Customer Constructor
    public Customer(String firstName, String lastName, String email, String password, double registrationAmount, String dob, String plan) {

        id_counter++;
        this.id = id_counter;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.registrationAmount = registrationAmount;
        this.dob = LocalDate.parse(dob);
        this.plan = ServicePlan.valueOf(plan);
    }

    // Overloaded Customer Constructor to Wrap Customer email
    public Customer(String email) {
        this.email = email;
    }

    @Override
    public String toString(){
        return "\nCustomer " +
                "[Customer Id: " + id +
                ", First Name: " + firstName +
                ", Last Name: " + lastName +
                ", Email Id: " + email +
                ", Password: " + password +
                ", Registration Amount: " + registrationAmount +
                ", Date of Birth: " + dob +
                ", Plan: " + plan+ "]\n";
    }

    // Declaration of necessary getter-setter methods

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    //Overriding Object.equals method
    @Override
    public boolean equals(Object o){
        if (o instanceof Customer){
            return this.email.equals(((Customer) o).email);
        }
        return false;
    }
}
// CustomerHandlingException Class

package custom_exceptions;

public class CustomerHandlingException extends Exception{
    public CustomerHandlingException(String errmsg){
        super(errmsg);
    }
}
// Enum

public enum ServicePlan {

    // Declaring the Service Plan Enums
    SILVER(1000),GOLD(2000),DIAMOND(5000),PLATINUM(10000);

    // Declaring the charges variable to hold the corresponding charges of each plan
    private double charges;

    // Constructor declaration
    private ServicePlan(double charges){
        this.charges = charges;
    }

    // Declaring .getCharges() method
    public double getCharges() {
        return charges;
    }

    // (Optional) toString Override method to return Plan Name and Charges
    @Override
    public String toString(){
        return name() + " plan charges: " + charges;
    }
}
// Validation Rules Class

import custom_exceptions.CustomerHandlingException;

import java.time.LocalDate;
import java.util.List;

public class ValidationRules {

    // Declaration of one method that will call all the validation methods
    public static Customer validateCustomerData(String firstName, String lastName, String email, String password, double registrationAmount, String dob, String plan, List<Customer> customerList) throws CustomerHandlingException {
        checkDuplicateCustomer(email, customerList);
        checkPlanAndAmount(registrationAmount, plan.toUpperCase());

        // Method deprecated. You may however, uncomment it and check if need be
        // Do make sure to uncomment the method definition below as well
        // checkPlan(plan.toUpperCase());
        checkAge(dob, customerList);
        System.out.println("\nEmail Id Registered Successfully");

        // Return the Customer Object with the data required to fill in the details in the ArrayList
        return new Customer(firstName,lastName,email,password,registrationAmount,dob,plan);
    }

    // No Duplicate Customers
    public static void checkDuplicateCustomer(String newEmail, List<Customer> customerList) throws CustomerHandlingException{
        Customer newCustomer = new Customer(newEmail);

        // As Email is our primary key and using .contains() match Email Id
        if (customerList.contains(newCustomer))
            throw new CustomerHandlingException("An account with this email has is already registered");

    }

    // Registration amount must match with the plan and if the plan is valid or not
    public static ServicePlan checkPlanAndAmount(double newAmount, String plan) throws CustomerHandlingException{

        // Parsing the String to get the Plan and using .getCharges() method to get the corresponding charges
        // using If condition to check if the amount is matching with the corresponding amount
        if (newAmount != ServicePlan.valueOf(plan).getCharges())
            throw new CustomerHandlingException("The plan amount does not match");

        // returning the Parsed Service Plan value
        return ServicePlan.valueOf(plan);
    }

    // Validate if plan is valid or not
//    public static ServicePlan checkPlan(String plan) throws IllegalArgumentException {
//        return ServicePlan.valueOf(plan.toUpperCase());
//    }

    // Customer's age must be greater than 18 years
    public static LocalDate checkAge(String dob, List<Customer> customerList) throws CustomerHandlingException{

        // Parsing the String input to get a LocalDate Object
        LocalDate newDOB = LocalDate.parse(dob);

        // Using the .now() method to get the current date
        // Using the .minusYears() method to subtract the required years from the current to get a reference date
        LocalDate checkDate = LocalDate.now().minusYears(18);

        // If the reference date is before the DOB then the condition fails
        if (checkDate.isBefore(newDOB))
            throw new CustomerHandlingException("You need to be 18 years of age to register");

        return newDOB;
    }


}
// Sample Data Class

import java.util.ArrayList;
import java.util.List;



public class SampleData {

    // Declaration of populateSampleData method
    public static List<Customer> populateSampleData(){
        try{

            // Declaration of ArrayList
            ArrayList<Customer> sampleData = new ArrayList<>();

            // Passing Sample Data thought .validateCustomerData() method and adding it into the ArrayList
            sampleData.add(ValidationRules.validateCustomerData("Abdul Ahad", "Sheikh", "abdulahadsheikh@xyz.com", "Abdul1234",5000,"1999-04-10","Diamond",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Bhushan", "Hippargi", "bhushanhippargi@abc.com", "Bhushu2345",10000,"1997-07-04","Platinum",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Ganesh", "Sagare", "ganeshsagare@abc.com", "Ganesh3456",2000,"1998-02-13","Gold",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Pranav", "Joshi", "pranavjoshi@abc.com", "Pranav4567",10000,"1998-11-23","Platinum",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Komal", "Kolhe", "komalkolhe@abc.com", "Komal5678",5000,"1997-10-27","Diamond",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Sakshi", "Palkar", "sakshipalkar@abc.com", "Sakshi6789",1000,"1997-05-15","Silver",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Tushar", "Pawar", "tusharpawar@abc.com", "Tushar7890",1000,"2001-01-19","Silver",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Mohan", "Talavar", "mohantalavar@abc.com", "Mohan8901",5000,"1998-08-18","Diamond",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Pranay", "Patil", "pranaypatil@abc.com", "Pranay9012",1000,"1996-09-09","Silver",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Rushikesh", "Mohite", "rushikeshmohite@abc.com", "Rush0123",2000,"1999-04-10","Gold",sampleData));
            sampleData.add(ValidationRules.validateCustomerData("Mohit", "Bijwar", "mohitbijwar@abc.com", "Mohit1234",10000,"2000-01-03","Platinum",sampleData));

            // Returning the ArrayList
            return sampleData;
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
// Tester Class

import custom_exceptions.CustomerHandlingException;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Tester {
    public static void main(String[] args) {

        // Using Try-with-resources block to initialize Scanner class
        try (Scanner in = new Scanner(System.in)) {

            // Initializing an Array List of Customer Object
            List<Customer> registerUsers = new ArrayList<>();

//            System.out.println(registerUsers);
//            System.out.println();

            // Adding Sample data to the ArrayList
            registerUsers = SampleData.populateSampleData();
//            System.out.println(registerUsers);

            // You can uncomment the above sysout comments to see the before and after the Sample Data is added to the registerdUser ArrayList

            // Initializing exit boolean as false
            boolean exit = false;

            // Starting
            while (!exit) {
                try{
                // Printing options for the users
                System.out.println("\n Select an option: ");
                System.out.println("1. SignUp for the service");
                System.out.println("2. SignIn to your account");
                System.out.println("3. Change your account password");
                System.out.println("4. Unsubscribe from the service:");
                System.out.println("5. Display all the existing Customers");
                System.out.println("0. Exit");

                System.out.println("\nEnter your Choice: ");
                int ch = in.nextInt();

                // Initiating Switch Case
                switch (ch) {

                    // Exiting case
                    case 0:
                        System.out.println("----------Exiting----------");
                        exit = true;

                        break;

                    // SignUp case
                    case 1:
                        try {
                            System.out.println("\n1. SignUp for the service");
                            System.out.println("Enter your details");

                            // first in.nextLine() to ensure that the function does not skip our input
                            in.nextLine();
                            System.out.print("First Name: ");
                            String firstName = in.nextLine();

                            System.out.print("Last Name: ");
                            String lastName = in.nextLine();

                            System.out.print("Date of Birth (YYYY-MM-DD): ");
                            String dob = in.nextLine();

                            System.out.print("Email Id: ");
                            String email = in.nextLine();

                            System.out.print("Password: ");
                            String password = in.nextLine();

                            System.out.println("\nChoose your plan from the following plans:");
                            for (ServicePlan plan : ServicePlan.values()) {
                                System.out.println(plan);
                            }
                            System.out.print("Enter your Selection: ");
                            String plan = in.nextLine().toUpperCase();
                            System.out.print("Amount to be Paid: ");
                            double registrationAmount = in.nextDouble();


                            registerUsers.add(ValidationRules.validateCustomerData(firstName, lastName, email, password, registrationAmount, dob, plan, registerUsers));
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(e.getMessage());
                        }
                        break;

                    // SignIn case
                    case 2:
                        try {
                            System.out.println("\n2. SignIn to your account");
                            System.out.print("Enter your Email Id: ");
                            // first in.nextLine() to ensure that the function does not skip our input
                            in.nextLine();
                            String email = in.nextLine();

                            // Finding the index of the Customer that matches the Email Id in our ArrayList
                            int index = registerUsers.indexOf(new Customer(email));

                            // indexOf returns -1 in case the value is not found in the ArrayList
                            // Hence if (index != -1) as the user for password and match it using the getPassword method and run it on the index we got from above
                            if (index != -1) {
                                System.out.print("Enter your Password " + registerUsers.get(index).getFirstName() + ": ");
                                String password = in.nextLine();

                                // Using equals method to match the Passwords
                                if (password.equals(registerUsers.get(index).getPassword())) {
                                    System.out.println("----------LogIn Successful----------");
                                    System.out.println("Welcome " + registerUsers.get(index).getFirstName() + " " + registerUsers.get(index).getLastName());

                                    // else case if the Password is incorrect
                                } else
                                    throw new CustomerHandlingException("Invalid Password!");

                                // else case if the Email Id is incorrect
                            } else
                                throw new CustomerHandlingException("Email Id not found. Please enter your registered Email Id or try Signing Up for the Services");
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(e.getMessage());
                        }
                        break;

                    // Change Password case
                    case 3:
                        try {
                            System.out.println("\n3. Change your account password");
                            System.out.println("Enter your Email Id: ");

                            // first in.nextLine() to ensure that the function does not skip our input
                            in.nextLine();
                            String email = in.nextLine();

                            // Finding the index of the Customer that matches the Email Id in our ArrayList
                            int index = registerUsers.indexOf(new Customer(email));

                            // indexOf returns -1 in case the value is not found in the ArrayList
                            // Hence if (index != -1) as the user for password and match it using the getPassword method and run it on the index we got from above
                            if (index != -1) {
                                System.out.print("Enter your new Password " + registerUsers.get(index).getFirstName() + ": ");

                                // using setPassword method to set a new Password
                                registerUsers.get(index).setPassword(in.nextLine());

                                // else case if the Email Id is incorrect
                            } else
                                throw new CustomerHandlingException("Email Id not found. Please try again");
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(e.getMessage());
                        }
                        break;

                    // Unsubscribe case
                    case 4:
                        System.out.println("\n4. Unsubscribe from the service: ");
                        System.out.print("Enter your Email Id: ");

                        // first in.nextLine() to ensure that the function does not skip our input
                        in.nextLine();
                        String email = in.nextLine();

                        // Finding the index of the Customer that matches the Email Id in our ArrayList
                        int index = registerUsers.indexOf(new Customer(email));

                        // indexOf returns -1 in case the value is not found in the ArrayList
                        // Hence if (index != -1) as the user for password and match it using the getPassword method and run it on the index we got from above
                        if (index != -1) {

                            // (Optional) Text message that is to be displayed to the user
                            System.out.println("You're Account and all the data will be deleted permanently.");
                            System.out.println("Hit Enter to delete all your data");

                            // (Optional) Taking Enter as an input from the user to
                            in.nextLine();

                            // Method to remove the user data from the ArrayList
                            registerUsers.remove(index);
                            System.out.println("----------Account Deleted----------");

                        } else
                            throw new CustomerHandlingException("Email Id not found!");
                        break;

                    // Display all case
                    case 5:
                        System.out.println("\n5. Display all the existing Customers: ");
                        System.out.println("Hit enter to display the data of all the existing Customers");
                        in.nextLine(); // This is skipped
                        in.nextLine(); // This is used to take Enter as an input from user

                        // Using for-each loop to print the details of the users
                        for (Customer c : registerUsers
                        ) {
                            System.out.println(c.toString()); // Using Overridden toString method to print the details
                        }
                        break;

                    // Default cease
                    default:
                        System.out.println("Invalid selection, Please enter a valid option");

                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                    System.out.println(e.getMessage());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}

Approach and explanation will be shared shortly, in the meantime I would encourage you to play with the code and figure out some optimization that can be made. Share in the comment section.

As always, Thank you so much for reading!

Hope this helps.

Happy Learning!

OOP with Java

Part 1 of 2

In this series, we will be posting content related to Object Oriented Programming with Java Module

Up next

PGDAC | OOP Java | Collections Framework

-Module taught by Madhura Anturkar