Question

In: Computer Science

Registry Java Programming 3) Planner Create a class called Planner. A Planner is a data structure...

Registry Java Programming

3) Planner

Create a class called Planner. A Planner is a data structure for storing events. The maximum capacity of the planner (physical size) is specified by the formal parameter of the constructor of the class.

Instance methods

  • int size(); returns the number of events that are currently stored in this Planner (logical size);

  • boolean addEvent( AbstractEvent event ); adds an event to the last position of
    this Planner. It returns true if the insertion was a success, and false if this Planner was already full;

  • AbstractEvent eventAt( int pos ); returns the event at the specified position in
    this Planner. This operation must not change this state of this Planner. The first event of the Planner is at position 0;

  • AbstractEvent remove( int pos ); removes the event at the specified position of
    this Planner. Shifts any subsequent items to the left (start of the array). Returns the event that was removed from this Planner;

  • void display( Date date ); the method display prints all the events that have a recurrence on the specified date;

  • void sort( Comparator< AbstractEvent > c ), the method passes the array of events and the comparator object to the method java.util.Arrays.sort;

The class overrides the method String toString(). An example of the expected format is given below.

4) Notifications:

Create a class called notifications that is sensitive to changes in the planner. Every time an item shows up in planner, the notifications class will display some kind of notification automatically on the screen. You need to use the observer design pattern.

These are the abstract classes:

// AbstractEvent.java : Java class to represent the AbstractEvent
import java.util.Date;

public abstract class AbstractEvent {
  
   // data fields
   private String description;
   private Date start_time;
   private Date end_time;
  
   // method to set the description of the AbstractEvent
   public void setDescription(String description)
   {
       this.description = description;
   }
  
   // method to set the start date for the AbstractEvent
   public void setStartTime(Date start)
   {
       this.start_time = start;
   }
  
   // method to set the end date for the AbstractEvent
   public void setEndTime(Date end)
   {
       this.end_time = end;
   }
  
   // method to return the description of the AbstractEvent
   public String getDescription()
   {
       return description;
   }
  
   // method to return the start date of AbstractEvent
   public Date getStartTime()
   {
       return start_time;
   }
  
   // method to return the end date of the AbstractEvent
   public Date getEndTime()
   {
       return end_time;
   }
  
   // The below 3 methods must be define by the concrete subclass of AbstractEvent
   // abstract method hasMoreOccurrences() whose implementation depends on the kind of event
   public abstract boolean hasMoreOccurrences();
   // abstract method nextOccurrence() whose implementation depends on the kind of event
   public abstract Date nextOccurrence();
   // abstract method init() whose implementation depends on the kind of event
   public abstract void init();
  
}
//end of AbstractEvent.java

1.2

//DailyEvent.java
import java.util.Calendar;
import java.util.Date;

public class DailyEvent extends AbstractEvent{
  
   // data field to store the number of recurrences
   private int num_consecutive_days;
   // helper field to return the next occurrence
   private int days_occurred = 0;
  
   // method to set the number of recurrences
   public void setNumberOfConsecutiveDays(int num_days)
   {
       this.num_consecutive_days = num_days;
   }

   // method to get the number of recurrences
   public int getNumberOfConsecutiveDays()
   {
       return num_consecutive_days;
   }
  
   // method to return if the event has more occurrences or not
   @Override
   public boolean hasMoreOccurrences() {
       // if days occurred < number of consecutive days , then next occurrence is valid
       if(days_occurred < num_consecutive_days)
           return true;
       return false;
   }

   // method to return the date of next occurrence
   @Override
   public Date nextOccurrence() {
      
       // if days_occurred >= number of recurrences, return null (as it exceeds number of recurrences)
       if(days_occurred >= num_consecutive_days)
           return null;
      
       // return the next occurrence date
       Calendar cal = Calendar.getInstance();
       cal.setTime(getStartTime());
       cal.add(Calendar.DATE, days_occurred);
       days_occurred++; // increment the number of days by a day
       return cal.getTime();
   }

   // method to re-initialize the state of the object so that a call to the method nextOccurrence() returns the date of the first occurrence of this event
   @Override
   public void init() {
       days_occurred = 0;
      
   }
   public String toString()
   {
       return("Start Date: "+getStartTime()+" End Date : "+getEndTime()+" Consecutive days of occurrence : "+num_consecutive_days);
   }


}
//end of DailyEvent.java

1.3

//WeeklyEvent.java
import java.util.Calendar;
import java.util.Date;

public class WeeklyEvent extends AbstractEvent{

   // data field to store the limit date
   private Date limit;
   // helper field to return the next occurrence
   private int num_days = 0;
  
   // method to set the limit date
   public void setLimit(Date limit)
   {
       this.limit = limit;
   }
  
   // method to return the limit date
   public Date getLimit()
   {
       return limit;
   }
  
  
   // method to return if the event has more occurrences or not
   @Override
   public boolean hasMoreOccurrences() {
      
       // check if the call to nextOccurrence will return a date within the limit
       Calendar cal = Calendar.getInstance();
       cal.setTime(getStartTime());
       cal.add(Calendar.DATE, num_days);
      
       if(cal.getTime().compareTo(limit) < 0)
           return true;
      
       return false;
   }

   // method to return the next occurrence date
   @Override
   public Date nextOccurrence() {
      
       Calendar cal = Calendar.getInstance();
       cal.setTime(getStartTime());
       cal.add(Calendar.DATE, num_days);
       // if next occurrence date > limit , return null, else return the next occurrence date
       if(cal.getTime().compareTo(limit) >= 0)
           return null;
       num_days += 7; // increment the number of days by 1 week
       return cal.getTime();
   }

   // method to re-initialize the state of the object so that a call to the method nextOccurrence() returns the date of the first occurrence of this event
   @Override
   public void init() {
       num_days = 0;
   }
  
   public String toString()
   {
       return("Start Date: "+getStartTime()+" End Date : "+getEndTime()+" Limit Date : "+limit);
   }

}
//end of WeeklyEvent.java

Solutions

Expert Solution

Planner.java

import java.util.*;

import java.text.SimpleDateFormat;

//Implement watcher to sent out notifications when events are added or removed

public class Planner implements watcher {

    //Store events in array

    AbstractEvent[] events;

    //Store size

    int currentSize;

    //Store observers list i.e whom to send out notifications

    ArrayList<Observer> observerList;

    public Planner(){

        observerList = new ArrayList<Observer>();

    }

    //initialize the events array

    public Planner(int size){

        observerList = new ArrayList<Observer>();

        events=new AbstractEvent[size];

        currentSize=0;

    }

    //return the current size

    int size(){

        return this.currentSize;

    }

    //returns true when addition of event is successful

    boolean addEvent(AbstractEvent event){

        //add to event

        if(currentSize<events.length){

            this.events[currentSize]=event;

            currentSize++;

            //notify event added

            notifyObservers("Event Added " + event.getDescription());

            return true;

        }

        else{

            return false;

        }

    }

    //returns the event at position

    AbstractEvent eventAt(int pos){

        if(pos<=currentSize && pos>=0)

            return events[pos];

        else

            return null;

    }

    //removes the element at given position

    AbstractEvent remove(int pos){

        AbstractEvent removedEvent=null;

        if (pos <= currentSize && pos >= 0)

            removedEvent=events[pos];

        for(int i=pos;i<(currentSize-1);i++){

            events[i]=events[i+1];

        }

        //Notification for Removal

        notifyObservers("Removed Event "+removedEvent.getDescription());

        return removedEvent;

    }

    //Displays the events which will reoccur on the given date

    void display(Date date){

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        System.out.println("Events that will reoccur on "+sdf.format(date));

        for(int i=0;i<currentSize;i++){

            AbstractEvent event=eventAt(i);

            while(event.hasMoreOccurrences()){

                if(date.equals(event.nextOccurrence())){

                    System.out.println(event.getDescription());

                }

            }

        }

    }

    //To sort the events

    void sort( Comparator< AbstractEvent > c ){

        Arrays.sort(events, c);

    }

    @Override

    public void registerObserver(Observer o) {

        observerList.add(o);

    }

    @Override

    public void unregisterObserver(Observer o) {

        observerList.remove(observerList.indexOf(o));

    }

    @Override

    public void notifyObservers(String notification) {

        for (Iterator<Observer> it = observerList.iterator(); it.hasNext();) {

            Observer o = it.next();

            o.showNotification(notification);

        }

    }

}

Test.java

import java.util.*;

public class Test {

    public static void main(String[] args) {

        //New Planner Object with 4 events

        Planner planner=new Planner(4);

        //New Notifications Class for notifications

        Notifications notifications=new Notifications();

        //for Automatic notifications with any addition or removal in planner object

        planner.registerObserver(notifications);

        //To get todays date

        Calendar cal = Calendar.getInstance();

        Calendar cal2= Calendar.getInstance();

        //Adding Events for Testing with start time today

        DailyEvent event1=new DailyEvent();

        event1.setDescription("First Daily Event");

        event1.setStartTime(cal.getTime());

        //End Date 4 days from today

        event1.setNumberOfConsecutiveDays(4);

    


        DailyEvent event2=new DailyEvent();

        event2.setDescription("Second Daily Event");

        event2.setStartTime(cal.getTime());

        cal2.add(Calendar.DATE,-2);

        //End date 2 days from today

        event2.setNumberOfConsecutiveDays(2);


        WeeklyEvent event3=new WeeklyEvent();

        event3.setDescription("First Weekly Event");

        cal2.add(Calendar.DATE, 12);

        event3.setStartTime(cal.getTime());

        //End date 14 days from today

        event3.setLimit(cal2.getTime());


        WeeklyEvent event4=new WeeklyEvent();

        event4.setDescription("Second Weekly Event");

        cal2.add(Calendar.DATE, -7);

        event4.setStartTime(cal.getTime());

        //End date 7 days from today

        event4.setLimit(cal2.getTime());


        DailyEvent event5=new DailyEvent();

        event5.setDescription("Third Daily Event");

        cal2.add(Calendar.DATE, 3);

        event5.setStartTime(cal.getTime());

        //End Date 10 days from today

        event5.setNumberOfConsecutiveDays(10);

        //Adding the events and printing if successful or not

        System.out.println(planner.addEvent(event1));

        System.out.println(planner.addEvent(event2));

        System.out.println(planner.addEvent(event3));

        System.out.println(planner.addEvent(event4));

        System.out.println(planner.addEvent(event5));

        //Removing second daily Event

        planner.remove(1);

        //Display Events which will reoccur 3 days from now

        cal.add(Calendar.DATE,7);

        planner.display(cal.getTime());

        

        

    }

}

Output

Today's Date 15/10/2019

Notifications.java

//Notifications class to send notifications

public class Notifications implements Observer{

    public void showNotification(String desc){

        System.out.println(desc);

    }

}

Observer.java

//Obseerver interface used with notifications Class

interface Observer {

    public void showNotification(String desc);

}

watcher.java

//Watcher interface used with plannar class

interface watcher {

    public void registerObserver(Observer o);

    public void unregisterObserver(Observer o);

    public void notifyObservers(String notification);

}

For indentation and output refer the above screenshots


Related Solutions

JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the...
JAVA Programming ECLIPSE IDE 1. Create an abstract class called Book. The class should declare the following variables: an instance variable that describes the title - String an instance variable that describes the ISBN - String an instance variable that describes the publisher - String an instance variable that describes the price - double an instance variable that describes the year – integer Provide a toString() method that returns the information stored in the above variables. Create the getter and...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String...
Java Programming CS 209 Data Structure 1. Create a method that takes an ArrayList of String and returns a copy of that ArrayList with no duplicates. The relative ordering of elements in the new ArrayList should be the same. Sample Input: {"qwerty", "asdfgh", "qwer", "123", "qwerty", "123", "zxcvbn", "asdfgh"} Sample Output: {"qwerty", "asdfgh", "qwer", "123", "zxcvbn"}
IN JAVA PLEASE Create a class called Child with an instance data values: name and age....
IN JAVA PLEASE Create a class called Child with an instance data values: name and age. a. Define a constructor to accept and initialize instance data b. include setter and getter methods for instance data c. include a toString method that returns a one line description of the child
Create a Java project called Lab3B and a class named Lab3B. Create a second new class...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class named Book. In the Book class: Add the following private instance variables: title (String) author (String) rating (int) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. Add a second constructor that receives only 2 String parameters, inTitle and inAuthor. This constructor should only assign input parameter values to title and...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class named Employee. In the Employee class: Add the following private instance variables: name (String) job (String) salary (double) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. (Refer to the Tutorial3 program constructor if needed to remember how to do this.) Add a public String method named getName (no parameter) that...
Create a Java project called 5 and a class named 5 Create a second new class...
Create a Java project called 5 and a class named 5 Create a second new class named CoinFlipper Add 2 int instance variables named headsCount and tailsCount Add a constructor with no parameters that sets both instance variables to 0; Add a public int method named flipCoin (no parameters). It should generate a random number between 0 & 1 and return that number. (Important note: put the Random randomNumbers = new Random(); statement before all the methods, just under the...
Create a new Java project called lab1 and a class named Lab1 Create a second class...
Create a new Java project called lab1 and a class named Lab1 Create a second class called VolumeCalculator. Add a static field named PI which = 1415 Add the following static methods: double static method named sphere that receives 1 double parameter (radius) and returns the volume of a sphere. double static method named cylinder that receives 2 double parameters (radius & height) and returns the volume of a cylinder. double static method named cube that receives 1 double parameter...
object oriented programming java Create a Student class that have two data members id (assign to...
object oriented programming java Create a Student class that have two data members id (assign to your ID) and name (assign to your name). Create the object of the Student class by new keyword and printing the objects value. You may name your object as Student1. The output should be like this: 20170500 Asma Zubaida
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT