我目前的问题是,我被分配去创建一个程序,这个程序应该在私有字段中为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类打印出列表。在添加了一些其他方法之后,我需要对代码进行更多的操作。
发布于 2019-11-03 03:40:35
您的问题是构造函数参数任务与您的类的字段具有相同的名称。
所以你在构造函数中给方法参数赋值,而不是给字段赋值。幸运的是,这两个不同的“任务”实体具有不同的类型,否则您甚至不会注意到有问题。
解决方案:使用
this.tasks = new String... 在构造函数的主体中!
而真正的答案是:你必须非常关注这些微妙的细节。通过对不同的事物使用不同的名称,你可以避免一整类的问题!
还请注意:一个名为Task的类包含一个任务列表,然后这些任务是字符串,这听起来有点奇怪。整体设计有点怪异...
https://stackoverflow.com/questions/58674513
复制相似问题