Home > Mobile >  Printing a concatenation of string using Formatter issue in java
Printing a concatenation of string using Formatter issue in java

Time:11-30

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 (d", "Subtotal", 400) "\n";
        String b =        fmt.format("%1s (d", "IVA 21%", 55) "\n";
        String c =  fmt.format("%1s (d", "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

CodePudding user response:

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 = s = s = %n",
     "Subtotal", 400, "IVA 21%", 55, "TOTAL", 555
);
    
System.out.println(result);

Output:

Subtotal 400      IVA 21%  55      TOTAL 555
  • Related