Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

java - How to align String on console output

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...