Search code examples
javastringformatter

Printing a concatenation of string using Formatter issue in java


Can someone explain this result to me and what is the best approach to do the same?:

public class Test {

    public static String test() {
        Formatter fmt = new Formatter();  
        String a = fmt.format("%1s %28d", "Subtotal", 400)+"\n";
        String b =        fmt.format("%1s %28d", "IVA 21%", 55)+"\n";
        String c =  fmt.format("%1s %28d", "TOTAL", 555)+"\n";
        return a+b+c;
    }
    public static void main(String argv[]) {
        System.out.println(test());
}
}

Outcome

Subtotal                          400
Subtotal                          400IVA 21%                           55
Subtotal                          400IVA 21%                           55TOTAL                    555


what i was expacting is this:

Subtotal    400
IVA 21%     55
TOTAL       555

Solution

  • You can format the entire resulting string in one go, since you need it to look as you see fit as a whole (if you're not using a, b, c parts separately).

    String result = String.format(
         "%s %3d %12s %3d %10s %3d %n",
         "Subtotal", 400, "IVA 21%", 55, "TOTAL", 555
    );
        
    System.out.println(result);
    

    Output:

    Subtotal 400      IVA 21%  55      TOTAL 555