You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java使用Formatter拼接字符串出现重复输出问题及解决方法

代码问题解析与优化方案

为什么会出现重复叠加的输出?

你用的是同一个Formatter对象,它内部维护着一个缓冲区。每次调用format()方法时,不会清空之前的内容,而是把新格式化后的字符串追加到缓冲区末尾。所以:

  • 第一次调用fmt.format()后,缓冲区内容是Subtotal 400,a就是这个内容加换行
  • 第二次调用时,会把IVA 21% 55追加到缓冲区,此时缓冲区内容变成Subtotal 400IVA 21% 55,b就是这个内容加换行
  • 第三次调用后,缓冲区又追加了TOTAL 555,c就是三段内容的叠加体加换行
    最后把a+b+c拼接输出,自然就出现了重复的内容。

实现需求的最佳方式

方法1:每次创建新的Formatter

每次调用格式化时都新建Formatter对象,避免内容叠加:

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

方法2:用String.format()(推荐)

String.format()是Java提供的简化API,内部会自动创建新的Formatter,代码更简洁易读:

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

方法3:调整格式符实现更美观的对齐

如果想要和你给出的期望输出一样,左边文本和右边数字间距更小且对齐,可以用左对齐格式符%-Ns(N是字符宽度),比如:

public class Test {
    public static String test() {
        // %-10s 表示左对齐,占10个字符宽度,确保文本对齐
        String a = String.format("%-10s %d\n", "Subtotal", 400);
        String b = String.format("%-10s %d\n", "IVA 21%", 55);
        String c = String.format("%-10s %d\n", "TOTAL", 555);
        return a+b+c;
    }
    public static void main(String argv[]) {
        System.out.println(test());
    }
}

运行后输出就会和你的期望一致:

Subtotal    400
IVA 21%     55
TOTAL       555

内容的提问来源于stack exchange,提问作者Badr Serhiri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:01:54