簡體   English   中英

嘗試在Java中打印Chars的2D數組

[英]Trying to print a 2D array of Chars in Java

我的程序根本不打印任何東西。

首先,我在一個單獨的類(板)中初始化了電路板:

       public class Board {
          public char board[][] = new char[9][9];   
          public void main(char[] args){

        for(int i=0; i<9; i++){
            board[i][0] = '_';
            board[i][8] = '_';
        }
        for(int h=0; h<9; h++){
            board[0][h] = '|';
            board[8][h] = '|';
        }

        for(int x=0; x>9; x++){
            for(int y=0; y>9; y++){
                System.out.println(board[x][y]);    
            }
        }
    }
}

然后在main中調用它,使用PrintLine “Hello World”來檢查代碼是否被訪問。 沒有錯誤被標記,但它也沒有打印任何東西。 主要是下面也只是為了檢查我沒有做任何簡單和愚蠢的事情:

    public static void main(String[] args) {  
    Ticker T = new Ticker();
    Board B = new Board();       
    for(int x=0; x>9; x++){
        for(int y=0; y>9; y++){
            System.out.println("Hello World");
            System.out.print(B.board[x][y]);

for循環的終止條件不正確。 應該是< ,而不是> 改成:

for(int x=0; x<9; x++){
    for(int y=0; y<9; y++){

你的循環條件有問題: -

for(int x=0; x>9; x++){
        for(int y=0; y>9; y++){

上面循環中的代碼永遠不會被執行。 它應該是: -

for(int x=0; x<9; x++){
        for(int y=0; y<9; y++){

除了for循環中的錯誤條件,你應該考慮使用

public class Board {
    public char board[][] = new char[9][9];

    // this is the constructor, it will be called if you say "new Board()"
    // the "main" method you had here will not be called automatically
    public Board() {
        for (int i = 0; i < 9; i++) {
            board[i][0] = '_';
            board[i][8] = '_';
        }
        for (int h = 0; h < 9; h++) {
            board[0][h] = '|';
            board[8][h] = '|';
        }

        for (int x = 0; x < 9; x++) {
            for (int y = 0; y < 9; y++) {
                // just a print so it does not make new lines for every char
                System.out.print(board[x][y]);
            }
            // new line once one column (board[x][0] - board[x][8]) is printed
            // note: you proably want to turn around the x and y above since
            // I guess you want to print rows instead of columns
            System.out.println();
        }
    }
}

它修復了一些問題

  • for循環的條件永遠不會成立
  • 用構造函數替換main方法,以便執行您在那里編寫的代碼
  • 更改為在一行中打印內部循環中打印的內容,因此它看起來像一塊板

如果你這樣做了

public static void main(String[] args) {  
    Ticker T = new Ticker();
    Board B = new Board(); // << this line triggers printing
    // ...
}

你應該看到一些董事會喜歡的東西

看看for(int x=0; x>9; x++){

它應該是for(int x=0; x<9; x++){

你可能想要x <9和y <9而不是>! ;-)這是條件循環。 如果為false,則循環退出。 在你的情況下,它總是錯誤的。

暫無
暫無

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

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