从方法创建另一个类的实例,并将其输出添加到地图

时间:2018-04-12 09:27:12

标签: java

我对java很新,并且建立了一个小型提醒应用程序,让人们可以跟踪活动。

该应用程序有2个类Activity和WhatsOn。

我试图了解如何在Activity.java类的addActivity类的范围内创建WhatsOn.java类的实例,该类将管道输出到创建了名为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;
    }
}

1 个答案:

答案 0 :(得分:3)

在add方法中,创建一个活动实例。然后将其添加到您的地图中。最后增加nextId。它应该是这样的:

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
}