简体   繁体   中英

Trouble reading a char array in java. What am I doing wrong?

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.

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.

You are hiding member variable in the constructor

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

it should be

 board= new char[row][column];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM