Reputation: 419
My program works. I was just wondering if there was a way for me to print my table by actually returning a string, and not just using System.out.print. In other words, I want to know if instead of having return null I can return a string that prints out my table.
/**
* Print the magic square in table form.
*/
public String toString() {
for (int row = 0; row < (magicSquare.length); row++) {
// row gets #row
System.out.print("\t");
for (int column = 0; column < (magicSquare[row].length); column++) {
//column gets #column
System.out.print(magicSquare[row][column] + "\t");
// when all column has been completed make new line
if (column == size - 1) {
System.out.print("\n");
}
}
System.out.print("\n");
}
return null;
}
Upvotes: 0
Views: 55
Reputation: 347194
The short answer is, yes you can. The long answer would involve replacing the System.out.print
statements with something like StringBuilder
, for example...
public String toString() {
StringBuilder sb = new StringBuilder(64);
for (int row = 0; row < (magicSquare.length); row++) {
// row gets #row
sb.append("\t");
for (int column = 0; column < (magicSquare[row].length); column++) {
//column gets #column
sb.append(magicSquare[row][column] + "\t");
// when all column has been completed make new line
if (column == size - 1) {
sb.append("\n");
}
}
sb.append("\n");
}
return sb.toString();
}
Upvotes: 2