英文:
How to make a toString() method for a 2D Array of Cells using the toString() method of Cell?
问题
我的任务是实现康威的生命游戏,但我卡在了如何在 toString()
方法中表示我的游戏地图(一个二维单元格数组)上。
我的toString()方法:
public String toString() {
int h;
int j;
String str;
str = null;
String[][] stringArray = new String[map.length][map.length];
for (h = 0; h < getWidth(); h++) {
for (j = 0; j < getHeight(); j++) {
Cell i = getCell(h, j);
stringArray[h][j] = i.toString() + " ";
}
}
int k;
int m;
for (k = 0; k < stringArray.length; k++) {
for (m = 0; m < stringArray.length; m++) {
str = stringArray[k][m];
}
}
return str;
}
正如你所看到的,我需要调用特定于单元格的 toString()
方法作为任务的一部分。
这个 toString()
方法如下:
public String toString() {
if (status == ECellStatus.DEAD) {
return ".";
} else {
return "#";
}
}
在实际代码中,我只获得了最后一个单元格的表示,但我想要像这样打印它:
. . . . .
. . # . .
. . . # .
. # # # .
. . . . .
希望有人可以帮助我解决这个问题。
英文:
My task is to implement Conway's Game of Life, but I'm stuck in representing my game-map (a 2D Array of Cells) in the toString()
method.
My toString() method:
public String toString() {
int h;
int j;
String str;
str = null;
String[][] stringArray = new String[map.length][map.length];
for (h = 0; h < getWidth(); h++) {
for (j = 0; j < getHeight(); j++) {
Cell i = getCell(h, j);
stringArray[h][j] = i.toString() + " ";
}
}
int k;
int m;
for (k = 0; k < stringArray.length; k++) {
for (m = 0; m < stringArray.length; m++) {
str = stringArray[k][m];
}
}
return str;
}
And as you see I need to call the cell specific toString()
method as part of the task.
This toString()
method looks like this:
public String toString() {
if (status == ECellStatus.DEAD) {
return ".";
} else {
return "#";
}
}
In the actual code I only get the representation of the last cell but I want to print it like that:
. . . . .
. . # . .
. . . # .
. # # # .
. . . . .
I hope somebody can help me out.
答案1
得分: 2
在第二个for循环中,您正在将str
重新分配给当前单元格的toString
,而不是在其上附加/添加,这可能是您打算做的操作。
要附加到str
,您可以执行以下操作:
for (k = 0; k < stringArray.length; k++) {
for (m = 0; m < stringArray.length; m++) {
str += stringArray[k][m];
}
}
这还需要您将str
初始化为非空值,所以代替
str = null;
您需要执行 str = "";
或类似的操作。
英文:
In the second for-loop, you are reassigning str
to the current Cell's toString
rather than appending/adding on to it, which is probably what you intended to do.
To append to str
, you can do:
for (k = 0; k < stringArray.length; k++) {
for (m = 0; m < stringArray.length; m++) {
str += stringArray[k][m];
}
}
This will also require you to initialize str
to a non-null value, so instead of
str = null;
you will need to do str = "";
or some equivalent of it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论