How to align String on console output

Mohammad Faisal picture Mohammad Faisal · Oct 9, 2012 · Viewed 59.8k times · Source

I've to write code for:

Multiplication Tables  Description: Print out the grade school multiplication table upto 12*12

I'd written the code:

public class tables {
    public static void main(String[] args) {
        //int[][] table = new int[12][12];
        String table="";
        for(int i=1; i<13; i++){
            for(int j=1; j<13; j++){
                //table[i-1][j-1] = i*j;
                table+=(i*j)+" ";
            }
            System.out.println(table.trim());
            table="";
        }
    }
}

But the problem is with the output format. I need the output in a matrix like fashion, each number formatted to a width of 4 (the numbers are right-aligned and strip out leading/trailing spaces on each line). I'd tried google but not find any good solution to my problem. Can anybody help me out?

Answer

Rohit Jain picture Rohit Jain · Oct 9, 2012

You can use format() to format your output according to your need..

    for(int i=1; i<13; i++){
        for(int j=1; j<13; j++){

           System.out.format("%5d", i * j);
        }
        System.out.println();  // To move to the next line.
    }

Or, you can also use: -

System.out.print(String.format("%5d", i * j));

in place of System.out.format..

Here's is the explanation of how %5d works: -

  • First, since we are printing integer, we should use %d which is format specifier for integers..
  • 5 in %5d means the total width your output will take.. So, if your value is 5, it will be printed to cover 5 spaces like this: - ****5
  • %5d is used to align right.. For aligning left, you can use %-5d. For a value 5, this will print your output as: - 5****