Want a multidimensional array but get a null pointer exception

后端 未结 4 1515
长情又很酷
长情又很酷 2020-12-21 18:24
  1 public class TestWin{
  2     public static void main(String[] args){
  3         int n;
  4         hexagon[][] board;
  5
  6         n = 4;
  7         board          


        
4条回答
  •  再見小時候
    2020-12-21 18:51

    Short Answer:

    As kwatford said what you need to do is this:

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

    Longer Explanation:

    Just to expand further. Your 2D array is; an array of pointers (or references in Java). This is what one row of the array will look like immediately after this call 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)
    

    You tried:

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

    which is the same as this:

    null.value = 'R';
    

    You have initialized your array using this line:

    board = new Hexagon[n][n];
    

    But you still need to initialize the elements in your array. This would initialize the first three:

    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
    

    Which would result in an array that looks like this:

        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)
    

    I remember banging my head on the table with this exact problem two years ago. I love stackoverflow

提交回复
热议问题