0

我在构建类时遇到问题,

以下代码抛出异常

public class Agent extends Board{    
    private static boolean arrow;
    private static boolean backmove;
    private static boolean gotGold;

    private static int atlocationX;
    private static int atlocationY;
    private static int faceposition; 
    private static int pathcounter;

    public boolean temporaryGold;
    public boolean temporaryWumpus;
    public boolean temporaryStench;
    public boolean temporaryBreeze;
    public boolean temporaryPit;

    int agentgui = 0;
    int label = 0;

    Block blockstorage[][] = new Block[4][4];
    KnowledgeBase kb = new KnowledgeBase();

    public Agent() {
        super();
    }

    public void Agent(){
        Agent.arrow = true;
        Agent.faceposition = 2;
        Agent.atlocationX = 0;
        Agent.atlocationY = 0;
        Agent.backmove = false;
        Agent.gotGold = false;
        Agent.pathcounter = 1;
    }
}

问题是,当我尝试添加

Agent agent = new Agent();

在我的其他一些课程中,例如:

public class Board {
    Agent agent = new Agent();
}

它返回一个错误:

线程“AWT-EventQueue-0”中的异常 java.lang.StackOverflowError

我也尝试过,但还是一样。

是什么导致了这个异常?

4

3 回答 3

5

您有一个带有间接递归调用的无限循环。

构造一个Board对象需要一个Agent对象,反之亦然

于 2012-08-29T13:27:38.820 回答
1

问题是你的Agent课程扩展Board

public class Agent extends Board

Agent类的构造函数中,您正在调用super()构造函数,该构造函数调用Board类构造函数

public Agent() {
    super();
 }

最后你的Board班级创建了一个Agent班级对象

public class Board {
 Agent agent = new Agent();

这使得无限循环导致:Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError.

编辑:根据您在评论您的代理类中回答问题

public class Agent{    
private static boolean arrow;
private static boolean backmove;
private static boolean gotGold;

private static int atlocationX;
private static int atlocationY;
private static int faceposition; 
private static int pathcounter;

public boolean temporaryGold;
public boolean temporaryWumpus;
public boolean temporaryStench;
public boolean temporaryBreeze;
public boolean temporaryPit;

int agentgui = 0;
int label = 0;

Block blockstorage[][] = new Block[4][4];
KnowledgeBase kb = new KnowledgeBase();

public void Agent(){
    Agent.arrow = true;
    Agent.faceposition = 2;
    Agent.atlocationX = 0;
    Agent.atlocationY = 0;
    Agent.backmove = false;
    Agent.gotGold = false;
    Agent.pathcounter = 1;
 }
}

您的 Board 课程应如下所示

public class Board {
 Agent agent = new Agent();
 // Now you can call your method of Agent class like following 
 agent.Agent()
}
于 2012-08-29T13:35:44.350 回答
0

代理扩展董事会,董事会需要代理。虚拟机花费无限时间尝试完成该任务。

就像一张纸,两面都写着“把我翻过来”。您花费无限的时间尝试遵循指示。

此外,请考虑在 StackOverflow 上回答一些问题,然后再提出更多“为我查找问题”类型的问题。

于 2012-08-29T13:37:29.463 回答