Question

So I'm trying to write a toString method that prints a representation of a variable-sized Board object with size N x N, so for example for N = 6 the representation would look like this:

===
    2r -- 2r 2r -- 2b
    -- -- 2r -- 3r --
    2r 3r 2r 3r -- 2b
    3r 1r 3r 2r 2r 2b
    2b 4r 3r 1r 3r 2b
    2b 2b 3b 2r 3b 1b
===

Every "Square" on this board is stored in a Square[]. My question is, since the size of this board is variable, how would I write a format string to be used by Formatter.format?

This is what I have so far, given squares is my Square[]:

/** Returns my dumped representation. */
@Override
public String toString() {
    Formatter out = new Formatter();
    String format = "Something here";
    out.format(format, squares);
    return out.toString();
}

I was thinking of trying to use a couple for loops and printing it out line by line, square by square, but I'm hoping theres a cleaner way to do this.

Was it helpful?

Solution

I would try to use a StringBuilder instead a Formatter:

final StringBuilder sb = new StringBuilder();
final int n = (int) Math.sqrt(squares.length);
for (int row = 0; row < n; row++) {
    for (int col = 0; col < n; col++) {
        final int offset = row * n + col;
        final Square square = squares[offset];
        sb.append(square.toString())

        final boolean lastCol = col == (n - 1);
        sb.append(lastCol ? "\n" : " ");
    }
}
return sb.toString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top