我的程序可以运行。我只是想知道是否有一种方法可以通过实际返回字符串来打印我的表格,而不仅仅是使用 System.out.print。 换句话说,我想知道是否可以返回一个打印出我的表的字符串,而不是返回 null。
/**
* 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;
}
最佳答案
简短的回答是,是的,可以。长答案将涉及用 StringBuilder
之类的内容替换 System.out.print
语句,例如......
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();
}
关于java - 另一种打印我的方法的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28686492/