简体   繁体   English

用Java打印2D对象数组?

[英]Printing 2D array of objects in Java?

I am starting a simple project where the user plays a version of Battleship against the computer. 我正在启动一个简单的项目,在该项目中,用户在计算机上玩《战舰》版本。 I would like to simply print out the game board for now. 我现在想简单地打印游戏板。 However, after initializing the board as a 2D array of object composed of the cells of the grid, I have encountered an error. 但是,将板初始化为由网格单元组成的2D对象阵列后,遇到了错误。 Rather than printing the cell type, which I have defined in the class, the code simply prints a grid of "null"s. 该代码不是打印我在该类中定义的单元格类型,而是仅打印“ null”的网格。 Any help here is much appreciated. 非常感谢您的任何帮助。

public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        grid[][] gameBoard = new grid[9][9];

        for (int x = 0; x < 9; x++) {
            for (int y = 0; y < 9; y++) {
                System.out.print(gameBoard[x][y] + " ");
            }
            System.out.println("");
        }

    }

}

public class grid {

    public String type;
    public String owner;
    public boolean positionCalled;

    public grid() {
        type = "_";
        owner = "";
        positionCalled = false;
    }

    public String toString() {
        return type;
    }

}

You only created the array, you did not create the single cells inside it. 您仅创建了数组,没有创建其中的单个单元格。

To do so, inside your loops: 为此,请在循环中执行以下操作:

gameBoard[x][y] = new grid();

You have to initialize your grid , 您必须初始化grid

for (int x = 0; x < 9; x++) {
    for (int y = 0; y < 9; y++) {
        gameBoard[x][y]=new grid();//initialize the grid
        System.out.print(gameBoard[x][y] + " ");
    }
    System.out.println("");
}

That's because you forgot to initialize 2d grid array objects after initialization. 那是因为您在初始化后忘记了初始化2d网格数组对象。 Add this line of code: 添加以下代码行:

for (int i = 0; i < 9; i++)
    for (int j = 0; j < 9; j++)
        gameboard[i][j] = new grid();

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

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