madauewo
madauewo

Reputation: 61

Java 2d array formatting?

I there, I am having problems formatting this 2d array. I was thinking about doing system.out.printf, but every time I do something like maybe %2f or something like that it doesn't work.

  public static void main(String[] args) {
    int t,i;
    int[][] table = new int[5][6];

    for (t = 0; t < 5; t++) {
        for (i=0;i < 6; i++) {
            table[t][i] = (t*6)+i+1;
            System.out.print(table[t][i] + "  ");
        }
        System.out.println();
    }

}

}

This is the output:

1  2  3  4  5  6  
7  8  9  10  11  12  
13  14  15  16  17  18  
19  20  21  22  23  24  
25  26  27  28  29  30  

The output should have the spaces perfectly aligned like this : http://prntscr.com/6kn2pq

Upvotes: 1

Views: 4984

Answers (4)

Omar Alnhdi
Omar Alnhdi

Reputation: 1

You can take my handle

for (t = 0; t < 5; t++) {
  for (i=0;i < 6; i++) {
    table[t][i] = (t*6)+i+1;
    if (table[t][i] > 9)
      System.out.print(table[t][i] + " ");
    else
      System.out.print(table[t][i] + "  ");
  }
  System.out.println();
}

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

Use format like this:

System.out.format("%4d", table[t][i]);

The output then looks like this:

   1   2   3   4   5   6
   7   8   9  10  11  12
  13  14  15  16  17  18
  19  20  21  22  23  24
  25  26  27  28  29  30

Or if you prefer to have the numbers aligned to the left:

System.out.format("%-4d", table[t][i]);

Which results in this output:

1   2   3   4   5   6   
7   8   9   10  11  12  
13  14  15  16  17  18  
19  20  21  22  23  24  
25  26  27  28  29  30  

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347334

Take a look at PrintStream#printf and String#format and Formatted Strings

Basically, for each row, each column needs to be formated to allow for a minimum of two spaces...

System.printf("%2d", table[t][i])

The next problem comes from the fact that the proceeding columns need extra space inbetween them ;)

System.printf("%2d%4s", table[t][i], "")

Which can result in something like...

 1     2     3     4     5     6    
 7     8     9    10    11    12    
13    14    15    16    17    18    
19    20    21    22    23    24    
25    26    27    28    29    30    

Upvotes: 1

Masudul
Masudul

Reputation: 21981

You should use printf instead of print

System.out.printf("%3d", table[t][i]);

Upvotes: 0

Related Questions