Java toString错误

时间:2012-12-06 02:06:45

标签: java class methods tostring multidimensional-array

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

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

另一方面,我得到括号围绕边缘,以及填充中间的逗号,我不知道为什么:

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

我的节目是对的,但我的班级需要帮助。

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 

1 个答案:

答案 0 :(得分:2)

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

当你调用Arrays.toString()方法时,它会打印一个开括号,跟随数组的内容(用逗号分隔),然后是一个闭括号。

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

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

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

[1, 2, 5, 8]

另一个例子是,如果你有一个填充空格的数组,你会得到:

[ ,  ,  ,  ,  , ]

(见空格?)

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