我正在开发一个使用类Map的程序,该类存储2D Tile对象数组以形成网格。在地图类中:
public class Map {
private int x = 80;
private int y = 40;
//store the entire map - a 50x50 2d array
private tile[][] grid = new tile[x][y];
public void Map() {
initialize();
grid[0][0].tile('.');
}
public void initialize() {
for (int i = 0; i < y; i++) {
for (int j = 0; j < x; j++) {
grid[j][i] = new tile();
}
}
}
public void display() {
for (int i = 0; i < y-1; i++) {
for (int j = 0; j < x-1; j++) {
System.out.println("Pass [" + j + "][" + i + "]");
System.out.print(grid[j][i].c());
}
System.out.println();
}
}
}
在tile类中:
public class tile {
private String title = "null";
private int id = 0;
private char c = ' ';
private boolean isVis = false;
public tile() {
id = 1;
format(id);
}
private void format(int n) {
c = 'A';
title = "foo";
isVis = false
}
public char c() { return c; }
}
运行程序时,我得到一个输出:
Pass [0][0]
Exception in thread "main" java.lang.NullPointerException
at Map.display(Map.java:22)
at rogue.main(rogue.java:7)
突出显示这一行:
System.out.print(grid[j][i].c());
我认为发生的事情是,一旦创建了类初始化。当我打印时
System.out.print(grid[j][i]);
它返回一个完整的&#34; nullnullnull&#34;我该怎么做才能确保对象初始化正确?
答案 0 :(得分:4)
public void Map()
不是构造函数(它是常规方法),因此在创建Map
实例时不会调用它,并且永远不会调用initialize
方法。
将其更改为
public Map()