weng tee
weng tee

Reputation: 392

create an instance of another class from a method and add its output to a map

I am newish to java and building a small reminder app that lets people keep track of activities.

The application has 2 classes Activity and WhatsOn.

I am trying to understand how I might go about creating an instance of the Activity.javaclass within the confines of my addActivitymethod in the WhatsOn.javaclass that would pipe the output into the created map called activities.

public class WhatsOn {
    //instance variables for WhatsOn class
    private static String today;
    private static int nextId;
    private Map<Integer, Activity> activities;

    // the constructor for the WhatsOn class
    public WhatsOn(Map<Integer, Activity> activities) {
        this.activities = activities;
        today = "010117";
        nextId = 1;
    }

    // This method should create an instance of Activity class  and then add it to the map referenced by the current value of nextId as the key
    public void addActivity (String aName, String aDate, String aTime) {
    // method required
    }
}

Activity.java

public class Activity {

    private String name;
    private String date;
    private String time;

    //constructor
    Activity(String name, String date, String time) {
        this.name = name;
        this.date = date;
        this.time = time;
    }

    //getters and setters
    public void setDate(String aDate) {
        this.date = aDate;
    }

    public void setTime(String aTime) {
        this.time = aTime;
    }

    public void setName(String aName) {
        this.name = aName;
    }

    public String getDate() {
        return this.date;
    }

    public String getTime() {
        return this.time;
    }

    public String getName() {
        return this.name;
    }
}

Upvotes: 1

Views: 1640

Answers (1)

vincrichaud
vincrichaud

Reputation: 2208

Inside your add Method, create an instance of activity. Then add it to your Map. Finally increase the nextId. It should look like this :

public void addActivity (String aName, String aDate, String aTime) {
    Activity actToAdd = new Activity(aName, aDate, aTime); //create an instance of Activity
    activities.put(nextId, actToAdd); //Add this intance to your Map
    nextId++; //increase the nextId
}

Upvotes: 4

Related Questions