想要一个多维数组但获得空指针异常

时间:2010-07-30 01:27:46

标签: java

  1 public class TestWin{
  2     public static void main(String[] args){
  3         int n;
  4         hexagon[][] board;
  5
  6         n = 4;
  7         board = new hexagon[n][n];
  8         board[0][0].value = 'R';

您好。 javac不喜欢我在第8行所做的事。有谁知道为什么?

4 个答案:

答案 0 :(得分:10)

已经有一段时间了,因为我看了很多Java,但你有没有尝试过这样做?

board[0][0] = new hexagon(); // or whatever its constructor is

答案 1 :(得分:8)

点击kwatford。你用第7行完成的就是告诉java在2维数组中为n * n Hexagon对象创建空间。

您仍需要为每个Hexagons调用new

基本上,您需要用以下内容替换第7行:

board = new Hexagon[n][n];
for(int i=0; i<n; i++)
    for(int j=0; j<n; j++)
        board[i][j] = new Hexagon();

答案 2 :(得分:5)

简答:

正如kwatford所说,你需要做的是:

board[0][0] = new hexagon(); // or whatever its constructor is

更长的说明:

进一步扩展。你的2D阵列是;指针数组(或Java中的引用)。这是在调用board = new hexagon[n][n];之后立即看到的一行数组:

    0      1      2      3      4      5       // column index, row index = 0
-------------------------------------------
|   |   |   |   |   |   |      |      |      |    // value
--- | ----- | ----- | ---------------------
    |       |       |      ...
    |       |       |
    |       |       |
    |       |       |
    |       |       v
    |       |       Null
    |       v       
    |       Null
    v
    Null (This means that it points to nothing)

你试过了:

board[0][0].value = 'R';

与此相同:

null.value = 'R';

您已使用以下行初始化数组:

board = new Hexagon[n][n];

但是你仍然需要初始化数组中的元素。这将初始化前三个:

board[0][0] = new hexagon(); // or whatever its constructor is
board[1][0] = new hexagon(); // or whatever its constructor is
board[2][0] = new hexagon(); // or whatever its constructor is

这会导致数组看起来像这样:

    0      1      2      3      4      5       // column index, row index = 0
-------------------------------------------
|   |   |   |   |   |   |      |      |      |    // value
--- | ----- | ----- | ---------------------
    |       |       |
    |       |       |
    |       |       |
    |       |       |
    |       |       v
    |       |       An instance of type Hexigoon (what you get when you type new Hexigon)
    |       v       
    |       An instance of type Hexigon (what you get when you type new Hexigon)
    v
    An instance of type Hexigon (what you get when you type new Hexigon)

我记得两年前这个确切的问题在我的桌子上敲我的头。我喜欢stackoverflow

答案 3 :(得分:1)

为了扩展kwatford的说法,如果数组类型是一个对象,初始化java中的数组会给你空值。如果你有一个原始数组,比如一个双精度数组,你可以从0开始作为数组中每个元素的条目。