0

我的代码可以在这里找到:http: //pastebin.com/tmzGGHzi

基本上,我的小动物所做的是它选择一个随机位置并移动到该位置,吃掉它路径上的所有演员。但是,第二次单击“step”时,它会在第 67 行引发 NullPointerException。这是 getAdjacentLocation() 方法引用空对象的问题,但我无法弄清楚,我的 AP 老师也无法弄清楚。

任何帮助是极大的赞赏!谢谢!

4

1 回答 1

0

getLocation() 方法返回 null。

Location loc = this.getLocation();
//Loc is now null, so the following call will result in a null pointer exception
Location newLoc = loc.getAdjacentLocation(getDirection());

这是因为它正在将自己从网格中移除/它正在吃掉自己

public ArrayList<Actor> getActors(){

    ArrayList<Actor> list = new ArrayList<Actor>();
    Grid<Actor> gr = getGrid();
    Location loc = getLocation();

    atLocation = atRandomLocation();

    if(!atLocation){

        setDirection(loc.getDirectionToward(randomLocation));

        //THIS RETURNS THE CRITTER'S CURRENT LOCATION!
        Actor a = gr.get(getLocation());

        if(a != null)
        //This critter is not going to be null, so it adds it to the list
            list.add(a);

    }else
        getRandomLocation();

    //This list contains all actors to be eaten
    return list;
}

您的方法所做的是检查它是否在该位置,将自身添加到列表中,然后自行吃掉!

public void processActors(ArrayList<Actor> actors){

    for(Actor a : actors)
        //This list only contains the critter
        a.removeSelfFromGrid();
}

您需要做的是找到它应该移动到的下一个位置,吃掉该空间中的任何演员,然后移动。

PS 显然,如果 Critter 是唯一的演员,它会默认吃掉自己。

于 2014-02-01T00:37:13.297 回答