簡體   English   中英

不打印二維數組

[英]Not Printing a 2D array

當我調用 printBoard 方法時,它不打印任何內容。 無法找出我寫錯了什么,如果錯誤不在其他地方,我該如何解決。

public class Board {
    private int rows;
    private int cols;
    private char[][] Board = new char[rows][cols];

    public Board(int row, int col) {
        rows = row;
        cols = col;

        for (int i = 0; i < Board.length; i++) {
            for (int j = 0; j < Board[i].length; j++) {
                Board[i][j] = '-';
            }
        }
    }

    public void printBoard() {
        for (int i = 0; i < Board.length; i++) {
            for (int j = 0; j < Board[i].length; j++) {
                System.out.print(Board[i][j]);
                System.out.print("|");
            }
            System.out.println(" ");
        }
    }
}

當您設置rowscols時,您不會在構造函數中重新創建 Board ,數組使用默認值 0 進行初始化。

它應該是:

public Board(int row, int col) {
    rows = row;
    cols = col;

    Board = new char[rows][cols]; // <-- reset array
                
    for (int i=0; i<Board.length ; i++) {
        for (int j=0; j<Board[i].length; j++) {
             Board[i][j]='-';
        }
   }
}

您可能已經假設Board數組將使用構造函數中設置的值進行初始化,但實際上構造函數是初始化實例變量后按照它們在類定義中出現的順序調用的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM