简体   繁体   中英

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. board.length is only the number of rows in your 2d array. 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). 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.

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.

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 }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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