1

I'm getting the error "Exception in thread "main" java.lang.NullPointerException" when I try to read an array value. Here is the code that I think causes the error.

        class Board
{
    private static char[][] board;

    public Board(int r, int c)
    {
        setRow(r);
        setColumn(c);
        char board[][] = new char[row][column];
    }

    public void getBoard()
    {
        for (int c = 1;c <= getColumn()-1 ;c++)
        {
            System.out.print("\t"+c);
        }
        System.out.print("\n");
        for (int r = 1; r <= getRow()-1; r++)
        {
            System.out.print(r);
            for (int c = 1; c <= getColumn(); c++)
            {
                System.out.print("\t" + board[r][c]);  //I think board[r][c] is causing it.
            }
            System.out.println("");
        }
        return;
    }
}

I can upload the whole file if need be.

Any help would be appreciated, this kept me up last night.

2
  • 1
    add a -1 to the last for loop, for (int c = 1; c <= getColumn()-1; c++) ` Commented Sep 26, 2012 at 14:47
  • 1
    Also, a "getXxx" method that doesn't return anything is misleading. You should probably call this "printBoard". Commented Sep 26, 2012 at 14:52

2 Answers 2

2

Replace

char board[][] = new char[row][column];

with

board = new char[row][column];

In the first statement, you're assigning a value to a local variable, not to the one of your instance.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that did it! Saved the day.
1

You are hiding member variable in the constructor

char board[][] = new char[row][column];

it should be

 board= new char[row][column];

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.