简体   繁体   中英

How to dynamically format Strings in Java

The following program prints the multiplication table 9xN which N is given by the user. My cells are fixed to be aligned only when the product is 2 numbers long.

What can I do so the cells will be aligned with any size of numbers?

    public static void main(String[] args) {

    //Reading the number n.
    System.out.print("Give a number: ");
    int n = StdIn.readInt();

    //Validating the number.
    while(n<1) {
        System.out.println("Please give a number greater or equal to 1");
        n = StdIn.readInt();
    }

    /*---------------------------------
    *
    *Lines 27-36 -> Creating the first
    *line and the first line's design.
    *
    ----------------------------------*/

    for (int i = 1; i <= n; i++) {
        System.out.printf("    %-4d", i);
    }
    System.out.println();
    System.out.print("  +");
    for (int i = 1; i <= n; i++) {
        System.out.print("-------+");
    }
    System.out.println();

    /*----------------------------------
    *
    *Lines 45-58 -> Printing the product
    *of the numbers and the design of
    *the table.
    *
    ----------------------------------*/

    for (int i = 1; i <=9 ; i++) {
        System.out.print(i + " |  ");
        for (int j = 1; j <= n; j++) {
            int a = (i * j);
            String b = "  |  ";
            System.out.printf("%2d %s", a, b);
        }
        System.out.println();
        System.out.print("  +");
        for (int k = 1; k <= n; k++) {
            System.out.print("-------+");
        }
        System.out.println();
    }
}
}

What can I do so the cells will be aligned with any size of numbers?

Not Aligned Cells

Aligned Cells

Thanks in advance.

To expand @Thomas Weller's comment a little, you need to separate the table cell value calculation loop from the table printing loop because you need to know the maximum number of digits in any cell before you start printing out the table so the 2 in %2d can be that max value instead.

EDIT: You will also need to know that max value in order to create the correct cell width instead of hard coding "-------+"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM