How to align String on console output

前端 未结 3 1388
你的背包
你的背包 2020-12-16 14:38

I\'ve to write code for:

\"Multiplication

3条回答
  •  生来不讨喜
    2020-12-16 15:15

    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****

提交回复
热议问题