首页 > 解决方案 > 创建tasks[]任务数组

问题描述

我当前的问题是,我被分配创建一个程序,该程序应在私有字段中分配 tasks[] 一个任务数组。然后在构造函数中创建 task[] 数组,赋予它 INITIAL_CAPAITY 的容量,并将 numTasks 设置为零。

我是新手,很困惑我可以解决这个问题

我曾尝试在构造函数中声明它,但没有运气。

任务.java

public class Task {
    private String name;
    private int priority;
    private int estMinsToComplete;

    public Task(String name, int priority, int estMinsToComplete) {
        this.name=name;
        this.priority=priority;
        this.estMinsToComplete = estMinsToComplete;
    }

    public String getName() {
        return name;
    }

    public int getPriority() {
        return priority;
    }

    public int getEstMinsToComplete() {
        return estMinsToComplete;
    }

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

    public void setEstMinsToComplete(int newestMinsToComplete) {
        this.estMinsToComplete = newestMinsToComplete;
    }

    public String toString() {
        return name+","+priority+","+estMinsToComplete;
    }


    public void increasePriority(int amount) {
        if(amount>0) {
            this.priority+=amount;
        }
    }

    public void decreasePriority(int amount) {
        if (amount>priority) {
            this.priority=0;
        }
            else {
                this.priority-=amount;
            }
        }
    }

HoneyDoList.java

public class HoneyDoList extends Task{
    private String[] tasks;
//this issue to my knowledge is the line of code above this

    private int numTasks;
    private int INITIAL_CAPACITY = 5;

    public HoneyDoList(String tasks, int numTasks, int INITIAL_CAPACITY,int estMinsToComplete, String name,int priority) {
        super(name,priority,estMinsToComplete);
        numTasks = 0;
        tasks = new String[]{name,priority,estMinsToComplete};
//as well as here^^^^^^^^
    }

我的预期结果是能够通过 honeydo 类打印出列表。添加一些其他方法后,我需要对代码进行更多操作。

标签: javaarraysclassextending-classes

解决方案


您的问题是您的构造函数参数任务与您的类的该字段具有相同的名称。

因此,您分配给构造函数中的方法参数,而不是字段。幸运的是,这两个不同的“任务”实体有不同的类型,否则你甚至不会注意到有问题。

解决方案:使用

this.tasks = new String... 

在构造函数体内!

真正的答案是:你必须非常注意这些微妙的细节。通过为不同的事物使用不同的名称,您可以避免一整类问题!

另请注意:一个名为 Task 的类包含一个任务列表,这听起来有点奇怪,然后是字符串。整体设计有点奇怪……


推荐阅读