1

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

1
  • You could use \t if the numbers are not too big. Commented Mar 24, 2015 at 5:13

4 Answers 4

1

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    
Sign up to request clarification or add additional context in comments.

2 Comments

or just add the spaces in the format ...printf("%2d ",... not that harder to read (eventually easier if having more fields).
@CarlosHeuberger Depends on your requirements, I find using %4s this way is easier to read in code, but that's me
0

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  

Comments

0

You should use printf instead of print

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

Comments

0

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

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.