0

I am looking to format the output of this code so that the totals of the rows and columns show up next to/below said row/column. I am getting the numbers correct, but spaces and char counts seem to be too unpredictable to format it correctly for any size square. Here is the code i currently have.

public void printSquare()
{
    for (int x = 0; x < square.length; x ++)
    {
        System.out.println();
        for (int j = 0; j < square.length; j++)
        {
            System.out.print("   " + square[x][j]);
        }
        System.out.println("  |  " + sumRow(x));

    }
    System.out.print(sumOtherDiag());
    for (int x = 0; x < square.length; x ++)
    {
        System.out.print("   ^");
    }
    System.out.println(sumMainDiag());
    for (int x = 0; x < square.length; x ++)
    {
        System.out.print("   " + sumCol(x));
    }
} 

And the output for this is..

   8   1   6  |  15

   3   5   7  |  15

   4   9   2  |  15
15   ^   ^   ^15
   15   15   15 

Are there any strategies in order to more reliably format something like this?

Parker Harris
  • 155
  • 1
  • 7
  • http://stackoverflow.com/questions/22416578/how-to-use-string-format-in-java Try using `String.format` as it allows you to do fixed-width spacing. – Compass Nov 03 '16 at 19:07
  • The other thing you could do: it probably starts with the fact that "8" is one char less than "15" ... so you could also print your single digit numbers as "08" for example. Then you need to worry less about spacing. But when you figure how to "format" with leading zeros, then you could also format with an additional space ... – GhostCat Nov 03 '16 at 19:10

1 Answers1

0

Instead of

  System.out.printf("   " + square[x][j]);

use

  System.out.printf("%4d", square[x][j]);    // 4 positions for right-aligned decimal

and so on for other similar statements.

MarianD
  • 13,096
  • 12
  • 42
  • 54