【问题标题】:Create tasks[] an array of task创建tasks[]任务数组
【发布时间】:2019-11-02 19:22:10
【问题描述】:

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

我是新手,对我能否解决这个问题感到困惑

我尝试在构造函数中声明它,但没有成功。

Task.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类打印出列表。添加一些其他方法后,我需要对代码进行更多操作。

【问题讨论】:

  • 请阅读minimal reproducible example 并相应地增强您的问题。我假设您遇到了某种编译器错误,或者您的问题到底是什么?
  • 它给了我一个类型不匹配的错误,说一个 String[] 不能被转换成另一个 String 或 int
  • 除了名称,其他变量(priority 和 estMinsToComplete)都是 int 并且您将它们传递给 String 数组。它肯定不会编译。 new String[]{name,priority,estMinsToComplete};
  • 您应该考虑一下您的设计,HoneyDo 是一个包含字符串数组的任务,您似乎在其中放置了 A 任务信息(名称、优先级、时间)

标签: java arrays class extending-classes


【解决方案1】:

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

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

解决方案:使用

this.tasks = new String... 

在构造函数体内!

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

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

【讨论】:

    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多