Malone2409
Malone2409

Reputation: 69

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

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.

Upvotes: 1

Views: 112

Answers (1)

ajc2000
ajc2000

Reputation: 834

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.

Upvotes: 2

Related Questions