0

无法填充网格。每次我这样做时,都会出现 stackoverflow 错误。这是我当前的代码:

public void removeSelfFromGrid() {
    Grid<Actor> grid = getGrid();
    int rows = grid.getNumRows();
    int cols = grid.getNumCols();
    for (int i=0; i<rows; i++) {
        for (int j=0; j<cols; j++) {
            Location loc = new Location(i, j);
            laugh = new CKiller();
            laugh.putSelfInGrid(grid, loc);
        }   
    }    
}

如果需要,这是构造函数

public CKiller()
 {
    Color c = null;
    setColor(c);
    getGrid();
    getLocation();
    location = new ArrayList<Location>();
    location.add(getLocation());
    setDirection(direction);
 }

这是错误(部分原因,太大而无法全部发布。只是重复了这两条语句):

java.lang.StackOverflowError
at info.gridworld.actor.Actor.putSelfInGrid(Actor.java:123)
at CKiller.removeSelfFromGrid(CKiller.java:120)

说这是问题

laugh.putSelfInGrid(grid, loc);
4

2 回答 2

0

执行以下操作:

laugh- 你是在 removeSelfFromGrid() 方法调用之前定义的吗?它之前没有指定类型。

- 变量location不应该是 ArrayList 吗?它可能是一个 Location 对象。

- intdirection已经定义了吗?

- 为什么要调用 getGrid() 和 getLocation()?他们没有做任何有益的事情。

- CKiller 是否继承了 Actor 类的 putSelfInGrid() 方法?

请包含 CKiller 类的完整代码以及包含 removeSelfFromGrid() 的主类。

于 2014-05-01T23:32:20.493 回答
0

我认为您的问题是您覆盖了该removeSelfFromGrid()方法。您应该已经创建了一个新方法,例如fillGrid().

当一个演员调用putSelfInGrid()时,如果Location它调用的当前有另一个演员removeSelfFromGrid(),您将覆盖它以用演员填充每个Location演员Grid。如果网格上有任何其他参与者,他们将调用removeSelfFromGrid(),这会导致再次填充网格等。

只需修复中的代码removeSelfFromGrid(),将其放入新方法并恢复以前的代码,您应该会很好。

于 2014-05-02T01:03:38.673 回答