繁体   English   中英

为什么我不能打印2D阵列?

[英]Why can't I print my 2D array?

在井字游戏中工作。

我一直在努力寻找打印二维数组的正确方法。 这是我目前正在使用的方法。 尝试在电路板上打印元素(或值,等等)。 怎么了

// display board indicating positions for token (x, o) placement 

public void printBoard(int size) {
    int col, row; 

    for (col = 0; col < size; col++)
        System.out.print("   " + col); 
        for (row = 0; row < size; row++) {
            System.out.print("\n" + row);
            System.out.print(" " + board[col][row] + "|");
            System.out.print(" _ _ _ _ _ _");
        }
}

假设size为board.length ,问题出在内部for循环中条件逻辑的问题。 board.length只是二维数组中的行数。 因此,除非行数等于列数,否则您的代码将无法工作。 2d数组中的列数等于2d数组中特定数组或行中元素的数量,可以将其写为board [i] .length(i是从0到board.length-1的数字)。 因此,我将更新您的方法以采用两个参数,而不是一个,

public void printBoard(int rows, int columns) {

    for (int i = 0; i < columns; i++){
        System.out.print("   " + i); 
        for (j = 0; j < rows; j++) {
            System.out.print("\n" + j);
            System.out.print(" " + board[j][i] + "|");
            System.out.print(" _ _ _ _ _ _");
        }
    }
}

然后,无论您在何处调用该方法,

printBoard(board.length, board[0].length);

请注意,以上内容仅在2d数组具有相等大小的列时才有效。

编辑:确保嵌套的for循环使用大括号{}正确格式化,因为您的外部for循环缺少一对大括号。

您忘记在循环中输入{} 当循环有多行时,必​​须用{}括起来

 public void printBoard(int size) {
        int col, row; 

        for (col = 0; col < size; col++){//here starts {
            System.out.print("   " + col); 
            for (row = 0; row < size; row++) {
                System.out.print("\n" + row);
                System.out.print(" " + board[col][row] + "|");
                System.out.print(" _ _ _ _ _ _");
            }
        }// here ends }
    }

暂无
暂无

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

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