【发布时间】:2012-12-06 02:06:45
【问题描述】:
我正在尝试为这个程序编写一个类,这个类创建一个对象移动的板。板应该看起来像一个盒子,四个角上有“+”,“-”垂直和“|”水平方向,空心:
+-----+
| |
| |
| |
| |
+-----+
另一方面,我的括号在边缘是水平的,中间是逗号,我不知道为什么:
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]
[ , , , , ]
我的程序是正确的,但我的课程需要帮助。
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
【问题讨论】:
-
~感谢 Luchian 的更正
-
错误是什么?尝试更改 toString() 方法。
-
是的,它与 toString 方法有关,但我似乎找不到它>.
-
[,,,] 我基本上得到了类似的东西,而不是 +--+
-
代码中唯一的加号是加法/连接运算符或增量运算符。不是包含“+”的单个字符串或字符。为什么您希望您的输出包含任何内容?
标签: java class methods tostring multidimensional-array