How to make a toString() method for a 2D Array of Cells using the toString() method of Cell?

go评论45阅读模式

How to make a toString() method for a 2D Array of Cells using the toString() method of Cell?

问题

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;
}

public String toString() {
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 &lt; getWidth(); h++) {
for (j = 0; j &lt; getHeight(); j++) {
Cell i = getCell(h, j);
stringArray[h][j] = i.toString() + &quot; &quot;;
}
}
int k;
int m;
for (k = 0; k &lt; stringArray.length; k++) {
for (m = 0; m &lt; 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() {
return &quot;.&quot;;
} else {
return &quot;#&quot;;
}
}

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

for (k = 0; k < stringArray.length; k++) {
for (m = 0; m < stringArray.length; m++) {
str += stringArray[k][m];
}
}

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 &lt; stringArray.length; k++) {
for (m = 0; m &lt; 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 = &quot;&quot;; or some equivalent of it.

• 本文由 发表于 2020年7月28日 01:05:45
• 转载请务必保留本文链接：https://go.coder-hub.com/63120097.html
• java
• multidimensional-array
• tostring

go 68

go 56

go 50

go 71