HeavenlyPanda
HeavenlyPanda

Reputation: 17

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.

Upvotes: 0

Views: 251

Answers (2)

slim
slim

Reputation: 41271

Consider using Java 8's StringJoiner:

public String toString() {
    StringJoiner iJoiner = new StringJoiner(System.getProperty("line.separator"));

    for (int i = 0 ; i < grid.length ; i++) {
        StringJoiner jJoiner = new StringJoiner("][", "[", "]");
        for (int j = 0 ; j < grid[i].length ; j++) {
            jJoiner.add("" + grid[i][j]);
        }
        iJoiner.add(jJoiner.toString());
    }
    return iJoiner.toString();
}

StringJoiner puts delimiters between (but not before or after) elements, and optionally adds a prefix or suffix.

It's worth looking at the source, for the elegant way it achieves this.

You could also do this in a Stream-oriented manner using Collectors.joining() -- which is a simple Collector implemented around StringJoiner:

 return Arrays.stream(grid)
     .map(row ->
         Arrays.stream(row)
             .mapToObj( x -> ""+x )
             .collect(Collectors.joining("][", "[", "]"))
     .collect(Collectors.joining(lineSeparator));
  • Makes a Stream<int[]> from the input int[][]
  • Using map() to process each int[]:
    • Make the int[] into an IntStream
    • mapToObj the IntStream into a Stream<String> with an item for each cell of the row
    • Collect the Stream<String> into a formatted row String "[1][2][3]"
    • map() therefore returns a Stream<String>
  • Collect the Stream<String> into one newline-separated String

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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();

Upvotes: 3

Related Questions