我对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;
}
}
答案 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
}