1

我有以下班级城市

public class City {

    public static boolean walls[][];
    public static int width, height;
    public static Human people[];
    public static ArrayList<Zombie> zombies = new ArrayList<Zombie>();

创建了一张随机地图(墙壁用于定义建筑物,城市中居住着人,并且在城市中创建了一个僵尸)。还有类人类和类僵尸

public class Human {
int x;
int y;
int d;

public Human(int x, int y, int d)
{
    this.x = x;
    this.y = y;
    this.d = d;
}

Zombie 和 Human 都包含决定他们在地图上移动的逻辑。因此,他们需要访问城市中的墙壁、人和僵尸来导航。该程序运行良好,它们是静态的,但是每当我创建一个新城市(以重置程序)时,它都会冻结,我认为这是因为静态变量。我尝试将它们设为私有,并在 City 中创建 getter 和 setter 方法并从 Human 和 Zombie 调用它们,但它总是说我不能以静态方式调用非静态方法。示例是:

public int peopleLength(){ //in City
    return people.length;
}

City.peopleLength() //in Human

可以让我知道我做错了什么或让我朝着正确的方向前进吗?提前致谢。

编辑:

if(StdDraw.isKeyPressed(32)){
world = new City(MAX_X,MAX_Y,80, 400);
}

因此,当按下空格键时,地图会被清除并重新绘制。有时它会工作 2 或 3 次,但大多数时候它只是进入黑屏并且不显示任何内容。

4

2 回答 2

1

任何一个:

  • 使变量非静态和私有,然后为它们添加 getter 和 setter 方法,或者
  • 在 City 上添加一个名为 reset() 的静态方法,将变量重置为其初始状态

我会走第一条路线。

于 2012-10-20T19:30:02.633 回答
0

使用 new 关键字创建 City 的实例。

City gotham = new City();

然后您将能够gotham在非静态上下文中引用该对象。

于 2012-10-20T19:32:04.960 回答