繁体   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