java - 从方法创建另一个类的实例并将其输出添加到 map

标签 java

我是 Java 的新手,正在构建一个小型提醒应用程序,让人们跟踪 Activity 。

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

我试图了解如何在 WhatsOn 中的 addActivity 方法范围内创建 Activity.java 类的实例。 java类,它将输出通过管道传输到创建的名为 activities 的 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/

相关文章:

java - 如何用Java打印Dijkstra算法的完整路径

java - JAX-RS 响应生成器生成的 JSON 实体不正确

java - 将结果集数据绑定(bind)到Getter Setter方法形成JSON字符串

java - xss 攻击问题——使用 servletoutputstream.write(b, 0, b.length);

java - ElasticSearch 端口 9300 连接被拒绝

java - 无法执行maven模块java类

java - 在 Java 8 中尝试通过 JDBC-ODBC 连接到 .accdb 文件时出现 ClassNotFoundException

java - 为什么我应该将 Boolean 作为参数而不是 "boolean"传递?

java - FIFO 顺序固定容量的线程安全集合

java - JTextPane 和换行符