简体   繁体   English

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

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

Working on a Tic Tac Toe game. 在井字游戏中工作。

I've been struggling to figure out the right way to print 2d arrays. 我一直在努力寻找打印二维数组的正确方法。 Here's the method I'm currently working on. 这是我目前正在使用的方法。 Trying to print the elements (or values, whatever) within the board. 尝试在电路板上打印元素(或值,等等)。 What's wrong here? 怎么了

// 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(" _ _ _ _ _ _");
        }
}

Assuming size is board.length , the problem lies in the logic of the condition in your inner for loop. 假设size为board.length ,问题出在内部for循环中条件逻辑的问题。 board.length is only the number of rows in your 2d array. board.length只是二维数组中的行数。 So unless the number of rows equals the number of columns, your code won't work. 因此,除非行数等于列数,否则您的代码将无法工作。 The number of columns in a 2d array equals the number of elements in a specific array or row within the 2d array, which can be written as board[i].length (i is a number from 0 to board.length - 1). 2d数组中的列数等于2d数组中特定数组或行中元素的数量,可以将其写为board [i] .length(i是从0到board.length-1的数字)。 So I would update your method to take in two parameters as opposed to one, 因此,我将更新您的方法以采用两个参数,而不是一个,

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(" _ _ _ _ _ _");
        }
    }
}

And then when you call the method wherever you do this, 然后,无论您在何处调用该方法,

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

Note the above will only work if the 2d array has equally-sized columns. 请注意,以上内容仅在2d数组具有相等大小的列时才有效。

Edit: Make sure your nested for-loops are properly formatted with curly brackets {} because your outer for-loop was missing a pair of curly brackets. 编辑:确保嵌套的for循环使用大括号{}正确格式化,因为您的外部for循环缺少一对大括号。

You forget to give {} in for loop. 您忘记在循环中输入{} when a loop has more than one line you must enclosed these statements with {} 当循环有多行时,必​​须用{}括起来

 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