java中二维数组的输出

bnlyeluc  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(450)
public class Main {
    boolean[][] ObstacleField; // board with mines marked as true
    int rows; // number of rows of the board
    int cols; // number of columns of the board
    int numObstacle;

    Main(int rows, int cols, int numMines) {
        this.rows = rows;
        this.cols = cols;
        this.numObstacle = num;
        this.ObstacleField = new boolean[rows][cols];
        Board();
    }

    public void Board() {
        int i = 0, j = 0;
        Random r = new Random();
        for (i = 0; i < this.numObstacle; ) {
            int x = r.nextInt(this.cols);
            int y = r.nextInt(this.rows);
            if (ObstacleField[x][y] != true) {
                ObstacleField[x][y] = true;
                i++;
            }
        }
    }

    public static void main(String[] args) {
        Main m = new Main(3, 3, 2);
        System.out.print(m.ObstacleField);

    }
}

嗨,首先我看了所有关于这个问题的问题,但是我找不到答案,我还是得到了同样的错误。通常我知道二维布尔数组在默认情况下是假的,但是我不能得到这样的输出。有什么问题,你能帮忙吗?
我把这个输出:

[[Z@6d06d69c
2wnc66cl

2wnc66cl1#

你可以用 Arrays.deepToString 获取 String 多维数组的表示:

System.out.print(Arrays.deepToString(m.ObstacleField));

输出:

[[false, false, true], [false, false, true], [false, false, false]]
3phpmpom

3phpmpom2#

该输出是obstaclefield的内存地址。
您必须迭代二维数组并打印每个位置:

for (int i = 0; i < m.ObstacleField.length; i++) {
    for (int j = 0; j < m.ObstacleField[i].length; j++) {
        System.out.print(m.ObstacleField[i][j] + "\t");
    }
    System.out.println();
}

相关问题