Search code examples
javaarraysstringtostring

How to convert a String Array to a String for my toString method


This is my toString method.

public String toString() {
   Life game = new Life(grid);
   String word;
       for (int row = 0; row < grid.length; row++) {
           for (int col = 0; col < grid[0].length; col++) {
               System.out.print("[" + grid[row][col] + "]");  
           }
           System.out.println();
       }
   word = "";
   return word;
}

I am trying to get the ("[" + grid[row][col] + "]"); into my String word. This is to create a game of life grid and I can't figure out how to put the array into a string representation.

Some sample of what it should look like if all the cells were dead. `

[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]
[0][0][0][0][0][0][0][0][0][0]

When I try word = word + "[" + grid[row][col] + "]"; i get...

[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]...

All in a straight line.


Solution

  • You are dealing with two issues here:

    • Collecting the output into a String - this can be done with StringBuilder class, and
    • Adding a newline to the output string - this is explained in this Q&A

    The end result should look as follows:

    StringBuilder res = new StringBuilder();
    String newline = System.getProperty("line.separator");
    for (int row = 0 ; row < grid.length ; row++) {
        for (int col = 0 ; col < grid[row].length ; col++) {
            res.append('[');
            res.append(grid[row][col]);
            res.append(']');
        }
        // Do not append the trailing newline
        if (row != grid.length-1) {
            res.append(newline);
        }
    }
    return res.toString();