我正在尝试为这个程序编写一个类,这个类创建一个可以移动对象的板。该板应该看起来像一个盒子,四个角上有“+”,垂直方向有“-”, “|”水平移动,中心空:
+-----+
| |
| |
| |
| |
+-----+
另一方面,我得到的括号水平地围绕边缘,逗号填充中间,我不知道为什么:
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]
我的程序是正确的,但我的类(class)需要帮助。
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
最佳答案
默认构造函数用空格填充数组:' '
。
当您调用 Arrays.toString()
方法时,它会打印一个开括号,后面是数组的内容(以逗号分隔),最后是一个闭括号。
例如,如果您有一个数组:
i a[i]
0 1
1 2
3 5
4 8
调用Arrays.toString(a)
打印出:
[1, 2, 5, 8]
再举一个例子,如果你有一个充满空格的数组,你会得到:
[ , , , , , ]
(看到空格了吗?)
这就是您收到该输出的原因。
关于Java toString 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13735841/