我在将对象放入链接列表时遇到问题。这是代码:
if(runTypes[k]==EMPTY){
Empty creature = new Empty();
}
else if(runTypes[k]==FISH){
Fish creature = new Fish();
}
else if (runTypes[k]==SHARK){
Shark creature = new Shark(starveTime);
}
DLinkedList.insertEnd(creature,runLengths[k]);
但是我收到错误:
RunLengthEncoding.java:89: cannot find symbol
symbol : variable creature
location: class RunLengthEncoding
DLinkedList.insertEnd(creature,runLengths[k]);
^
1 error
Empty()是Fish and Shark的超类。
以下是循环LinkedList类中insertEnd方法的代码:
public void insertEnd(Empty creature, int number) {
DListNode3 node = new DListNode3(creature);
head.prev.next = node;
node.next = head;
node.prev = head.prev;
head.prev=node;
node.amount = number;
size++;
}
以下是节点的代码: 公共类DListNode3 {
public Empty creature;
public DListNode3 prev;
public DListNode3 next;
public int amount;
DListNode3(Object creature) {
this.creature = creature;
this.amount = 1;
this.prev = null;
this.next= null;
}
DListNode3() {
this(null);
this.amount = 0;
}
}
我不知道该怎么做,我是OOP的新手。有什么建议吗?
答案 0 :(得分:3)
当我们按如下方式声明变量时 -
if(runTypes[k] == EMPTY) {
Empty creature = new Empty();
}
该变量是声明它的块({}
)的本地变量。并且在那个街区外面看不到它。
你正试图在外面使用它 -
DLinkedList.insertEnd(creature,runLengths[k]);
不可见的地方。所以,编译器抱怨。
您可以执行以下操作来解决问题 -
Empty creature = null; //Empty can be the variable type, it's the parameter type in the insertEnd method
if(runTypes[k] == EMPTY) {
creature = new Empty(); //no problem, it's the same class
} else if(runTypes[k] == FISH) {
creature = new Fish(); //no problem, Fish is a subclass
} else if (runTypes[k] == SHARK) {
creature = new Shark(starveTime); //no problem, Shark is a subclass of Empty
}
DLinkedList.insertEnd(creature, runLengths[k]);