简体   繁体   English

不打印二维数组

[英]Not Printing a 2D array

When I call the printBoard method it doesn't print anything.当我调用 printBoard 方法时,它不打印任何内容。 Could't find out what I wrote wrong How could I fix that if the error is nowhere else.无法找出我写错了什么,如果错误不在其他地方,我该如何解决。

public class Board {
    private int rows;
    private int cols;
    private char[][] Board = new char[rows][cols];

    public Board(int row, int col) {
        rows = row;
        cols = col;

        for (int i = 0; i < Board.length; i++) {
            for (int j = 0; j < Board[i].length; j++) {
                Board[i][j] = '-';
            }
        }
    }

    public void printBoard() {
        for (int i = 0; i < Board.length; i++) {
            for (int j = 0; j < Board[i].length; j++) {
                System.out.print(Board[i][j]);
                System.out.print("|");
            }
            System.out.println(" ");
        }
    }
}

You do not recreate Board in the constructor when you set rows and cols , the array is initialized with default 0 values.当您设置rowscols时,您不会在构造函数中重新创建 Board ,数组使用默认值 0 进行初始化。

It should be:它应该是:

public Board(int row, int col) {
    rows = row;
    cols = col;

    Board = new char[rows][cols]; // <-- reset array
                
    for (int i=0; i<Board.length ; i++) {
        for (int j=0; j<Board[i].length; j++) {
             Board[i][j]='-';
        }
   }
}

You might have assumed that Board array would be initialized with the values set in the constructor, but in fact the constructor is invoked after initializing the instance variables in the order of their appearance in the class definition.您可能已经假设Board数组将使用构造函数中设置的值进行初始化,但实际上构造函数是初始化实例变量后按照它们在类定义中出现的顺序调用的。

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

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