简体   繁体   中英

error creating 2d array of type object

So, I'm trying to make a board that holds objects called Nodes but for some reason, when I try to create the array of Nodes, I get the error in the title but don't understand why. From everything I've learned,

"public static Node[][] board = new Node[11][11];"

should be a valid statement. All I want to do here is make an array that's 11x11. I fill the array in a loop later.

I've looked for help on here and elsewhere but can't find anything to solve the problem. Some ideas are close but the problem still persists. Any help would be great.

public class Board {

    //creates the board
    public static Node[][] board = new Node[11][11];

    //create an empty node and place it in  every other location
    //like a checkered board.
    for(int i = 0; i < board.length; i++) {
        for (int j = 0; j< board[i].length; j+=2) {
            if(i%2 == 0) {//if it is an even row start at 0
                board[i][j] = new Node(null);
            }else if(j+1 < board[i].length){//if odd row and less than length, start at 1
                board[i][j+1] = new Node(false);
            }else{
            }
        }
    }


}

You need a method or constructor, I don't believe Java lets you put statements in the class body.

public class Board {

    // Creates the board
    public static Node[][] board = new Node[11][11];

    public Board() {
        // Create an empty node and place it in  every other location
        // like a checkered board.
        for(int i = 0; i < board.length; i++) {
            for (int j = 0; j< board[i].length; j+=2) {
                if(i%2 == 0) {
                    // Even row start at 0
                    board[i][j] = new Node(null);
                }
                else if(j+1 < board[i].length) {
                    // Odd row and less than length, start at 1
                    board[i][j+1] = new Node(false);
                }
            }
        }
    }
}

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