0

我正在尝试为这个程序编写一个类,这个类创建一个对象移动的板。板应该看起来像一个盒子,四个角上有“+”,“-”垂直,“|” 以空中心水平移动:

+-----+
|     |
|     |
|     |
|     |
+-----+

另一方面,我的括号在边缘水平排列,中间用逗号填充,我不知道为什么:

[ , , , , ] 
[ , , , , ]
[ , , , , ] 
[ , , , , ] 
[ , , , , ] 

我的程序是正确的,但我的课程需要帮助。

import java.util.Arrays;
import java.util.Random;

public class Board {

    private char [][] theBoard;

    public Board() { 
        this(10, 25); 
    }


    public Board (int rows, int cols) {
        if (rows < 1 || rows>80) {
            rows = 1;
        }
        if (cols<1 || cols > 80) {
            cols = 1;
        }
        theBoard = new char [rows][cols];
        for (int row = 0; row < theBoard.length; row++) {
            for (int col = 0; col < theBoard[row].length; col++)
                theBoard[row][col] = ' ';
    }
    }

        public void clearBoard() {
        for (int row = 0; row < theBoard.length; row++ ) {
        for (int col = 0; col < theBoard[row].length; col++) {
      if (theBoard[row][col] < '0' || theBoard[row][col] > '9') {
      theBoard[row][col] = ' ';   
    }
    }
    }
    }

            public void setRowColumn(int row, int col, char character) {
           theBoard[row][col] = character;
        }

            public char getRowColumn(int row, int col) {
            return theBoard[row][col];
        }

        public String toString() {
    StringBuilder strb = new StringBuilder();
    for (char[] chars : theBoard) {
        strb.append(Arrays.toString(chars) + "\n");
    }
    return strb.toString();
    }
    public static void main(String [] args)
   {
      Board aBoard, anotherBoard;

      System.out.println("Testing default Constructor\n");
      System.out.println("10 x 25 empty board:");

      aBoard = new Board();
      System.out.println(aBoard.toString());

      System.out.println();

      // And, do it again
      System.out.println("Testing default Constructor again\n");
      System.out.println("10 x 25 empty board:");

      anotherBoard = new Board();
      System.out.println(anotherBoard.toString());

   } // end of method main
} // end of class 
4

1 回答 1

2

默认构造函数用空格填充数组:' '.

当您调用该Arrays.toString()方法时,它会打印一个左括号,然后是数组的内容(以逗号分隔),然后是一个右括号。

例如,如果您有一个数组:

i  a[i]
0   1
1   2
3   5
4   8

调用Arrays.toString(a)打印出来:

[1, 2, 5, 8]

再举一个例子,如果你有一个充满空格的数组,你会得到:

[ ,  ,  ,  ,  , ]

(看到空格了吗?)

这就是您收到该输出的原因。

于 2012-12-06T02:14:25.673 回答