打印方法的另一种方法是什么?

时间:2015-02-24 00:56:09

标签: java

我的计划有效。我只是想知道是否有办法通过实际返回字符串来打印我的表,而不仅仅是使用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;
}

1 个答案:

答案 0 :(得分:2)

简短的回答是,是的,你可以。长答案将涉及用System.out.print替换StringBuilder语句,例如......

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