简体   繁体   English

创建类型对象的二维数组时出错

[英]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. 因此,我试图制作一个可容纳称为Nodes的对象的电路板,但由于某种原因,当我尝试创建Nodes数组时,出现标题错误,但不明白为什么。 From everything I've learned, 从我学到的一切,

"public static Node[][] board = new Node[11][11];" “公共静态节点[] []板=新节点[11] [11];”

should be a valid statement. 应该是有效的声明。 All I want to do here is make an array that's 11x11. 我在这里要做的只是创建一个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. 您需要一个方法或构造函数,我不相信Java允许您在类主体中放置语句。

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);
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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