簡體   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