2

Here is the code example. I want to create a 1 dimensional array of objects, give them values, use it in other methods, then print it out as a 2 dimensional array.

At first i want to print the starting board, but i get NullPointException when i try to loop throught the array. The 2 dimensional array is a 6x6 matrix.

public class Field{
    int diceCount, playerNumber;

    //get and set methods etc.
}

public class Board{
    public Field[] board = new Field[36];

    public void boardBuilder(){
        for(int i = 0; i < board.length; i++){
            board[i] = new Field();
            //give value to the Fields      
        }
    }
}

public class IoMethods{
    public Board board = new Board();

    public void boardPrintOut(){
        int helper;
        for(int i = 0; i < 6; i++){
            for(int j = 0; j < 6; j++){
                //The next line is where it gets the Exception
                helper = board.board[i*6 + j].getPlayerNumber();

                //print part
            }
        }
    }
}
1
  • Sorry it's kind of late. This is just a sorter example of the code and i made a few typos. Commented Apr 16, 2016 at 22:40

3 Answers 3

2

You did not build the board. Do board.boardBuilder() before looping through the members

board.boardBuilder()
for(int i = 0; i < 6; i++){
    for(int j = 0; j < 6; j++){
        //The next line is where it gets the Exception
        helper = board.board[i*6 + j].getPlayerNumber();
            //print part
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

This line public Field[] board = new Field[36]; creates an array of length 36 which can contain Field objects. But now all of its 36 cells are null. So when you try to access some board[i] you're accessing null.

Solution: Write a constructor for your Board class and inside that write what you've written inside boardBuilder() or simply call this.boardBuilder():

public Board(){
    for(int i = 0; i < board.length ; i++)
    {
        board[i] = new Field();
    }
}

Comments

1

reason is boardBuilder() method is not called.

Now you either call board.boardBuilder() before you try access it,

Or better create a constructor for Board class like -

Board() {
    this.boardBuilder();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.