Monday, 6 November 2023

Define a class Date (Day, Month, Year) with functions to accept and display it. Accept date from user. Throw user defined exception “invalid Date Exception” if the date is invalid.

 

Define a class Date (Day, Month, Year) with functions to accept and display it. Accept date from user. Throw user defined exception “invalid Date Exception” if the date is invalid. 

class InvalidDateException extends Exception {

    public InvalidDateException(String message) {

        super(message);

    }

}

 

class Date {

    private int day, month, year;

 

    public Date(int day, int month, int year) {

        this.day = day;

        this.month = month;

        this.year = year;

    }

 

    public void displayDate() {

        System.out.println("Date: " + day + "/" + month + "/" + year);

    }

 

    public boolean isValidDate() {

        if (year >= 1900 && year <= 2100) {

            if (month >= 1 && month <= 12) {

                if (day >= 1 && day <= 31) {

                    if (month == 4 || month == 6 || month == 9 || month == 11) {

                        return day <= 30;

                    } else if (month == 2) {

                        if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {

                            return day <= 29;

                        } else {

                            return day <= 28;

                        }

                    }

                    return true;

                }

            }

        }

        return false;

    }

}

 

public class Main {

    public static void main(String[] args) {

        try {

            int day = 31;

            int month = 12;

            int year = 2023;

 

            Date date = new Date(day, month, year);

 

            if (date.isValidDate()) {

                date.displayDate();

            } else {

                throw new InvalidDateException("Invalid Date Exception: The entered date is not valid.");

            }

        } catch (InvalidDateException e) {

            System.err.println(e.getMessage());

        }

    }

}