Search code examples
javaformatnumbersline

Proper data formatting and alignment


How can I format these columns of numbers properly? Meaning all numbers should be aligning with each other in columns.

I tried to use format but still couldn't fix the alignment. Like :

    625        50      25
    676        52      26
    729        54      27
    784        56      28
    841        58      29
    900        60      30
    961        62      31
    1024       64      32
    1089       66      33
    1156       68      34
    1225       70      35
    1296       72      36

Output

    625     50      25
    676     52      26
    729     54      27
    784     56      28
    841     58      29
    900     60      30
    961     62      31
    1024        64      32
    1089        66      33
    1156        68      34
    1225        70      35
    1296        72      36

   public class TestFormat {
    
        public static void main(String[] args) {
            for(int i = 25; i<50;i++) {
                int sum = i * i;
                int add = i + i;
                int div = (i+i)/2;
                System.out.println("\t" + sum + "\t\t" + add + "\t\t" + div);
            }
    
        }
    }


Solution

  • You could use System.out.printf with left-justified flag -:

    // 6 chars left justified for each column
    System.out.printf("%-6d %-6d %d%n", sum, add, div); 
    

    See formatting tutorial for more details