1

I'm having trouble putting an object into a linked list. Here is the code:

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]);

However I get an error:

RunLengthEncoding.java:89: cannot find symbol
symbol  : variable creature
location: class RunLengthEncoding
        DLinkedList.insertEnd(creature,runLengths[k]);  
                              ^
1 error

Empty() is a super class to Fish and Shark.

Here is the code for the insertEnd method in the circularly LinkedList class:

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++;
}

And here is the code for the node: public class 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;
    }
    }

I don't know what to do and I am new to OOP. Any advice?

4

1 回答 1

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]);
于 2013-06-06T22:52:12.693 回答