我是 Java 的新手,正在构建一个小型提醒应用程序,让人们跟踪 Activity 。
该应用程序有 2 个类 Activity 和 WhatsOn。
我试图了解如何在 WhatsOn 中的
类,它将输出通过管道传输到创建的名为 addActivity
方法范围内创建 Activity.java
类的实例。 javaactivities
的 map 中。
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;
}
}
最佳答案
在您的 add 方法中,创建一个 Activity 实例。然后将其添加到您的 map 。最后增加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
}
关于java - 从方法创建另一个类的实例并将其输出添加到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792893/