1

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:

enter image description here

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.

Saif Ahmad
  • 1,118
  • 1
  • 8
  • 24
Ryukaizan
  • 13
  • 4
  • if your values are till 99, if your current value is lowest then 10, add a space before him – AsfK Feb 20 '18 at 06:39

2 Answers2

1

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
Saif Ahmad
  • 1,118
  • 1
  • 8
  • 24
1

To print a number with exactly four characters (padded by spaces) use this format:

System.out.printf("%4d", square[row][col]);
Henry
  • 42,982
  • 7
  • 68
  • 84