Reputation: 13
so this is the code I have below:
public void printSquare() {
for (int row = 0; row < square.length; row++) {
for (int col = 0; col < square.length; col++) {
System.out.printf(square[row][col] + "%-3c", ' ');
}
System.out.println();
}
}
I'm trying to print them to look like this:
But my output is:
***** Square 2 *****
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
I've been messing around with printf for awhile now and I can't seem to figure out how to print it neatly. I'm barely hitting Java for my second semester in school, so I'm not that adept at coding yet. Any advice would help.
And if my coding is unorthodox or looks bad, please call me out on it so I can fix it.
Thank you.
Upvotes: 1
Views: 164
Reputation: 43728
To print a number with exactly four characters (padded by spaces) use this format:
System.out.printf("%4d", square[row][col]);
Upvotes: 1
Reputation: 1171
You can try adding a tab space instead of manually adding space. Tab space will take care of issue of digit with space
public static void printSquare(int[][] square) {
for (int row = 0; row < square.length; row++) {
for (int col = 0; col < square.length; col++) {
System.out.print(square[row][col]+"\t");
}
System.out.println();
}
}
OUTPUT
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
Upvotes: 1