gpt4 book ai didi

java - 传递不同类Java的对象

转载 作者:行者123 更新时间:2023-11-29 05:42:31 25 4
gpt4 key购买 nike

我在将对象放入链表时遇到问题。这是代码:

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 和 Shark 的父类(super class)。

下面是循环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++;
}

这是节点的代码: 公共(public)类 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 的新手。有什么建议吗?

最佳答案

当你我们声明一个变量如下-

if(runTypes[k] == EMPTY) {
Empty creature = new Empty();
}

该变量是声明它的 block ({}) 的本地变量。而且在那个街区之外是不可见的。

而你正试图在外面使用它 -

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

关于java - 传递不同类Java的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16973269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com