gpt4 book ai didi

Java 的格式说明符重复打印输出

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:28 25 4
gpt4 key购买 nike

我编写了一个 Java 程序来打印从 1 到 10 的数字,并采用空格格式。使用 java.util.Formatter,我没有得到预期的输出。为什么?

预期输出是:

1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10

这是我的代码:

import java.util.*;

public class CountTo10 {
static void formatterFunc() {
String myString = "";
Formatter fmt = new Formatter();

for(int i=1; i<=10; i++) {
fmt.format("%4d", i);
myString = myString + fmt;
}
System.out.println(myString);
}

static void stringFunc() {
String myString = "";
for(int i=1; i<=10; i++) {
myString = myString + i + " ";
}
System.out.println(myString);
}

public static void main(String args[]) {
stringFunc();
System.out.println("\n");
formatterFunc();
}
}

最佳答案

java.util.Formatter 的某些构造函数采用 Appendable 作为参数。但根据 Java API docs默认构造函数(您正在使用的构造函数)使用 StringBuilder。 (StringBuilder 实现 Appendable)

The destination of the formatted output is a StringBuilder ...

因此,每次调用 fmt.format() 时,您每次都会附加到相同的 StringBuilder

您选择的修复方法是:

  1. 放弃String连接,仅使用Formatter:

    static void formatterFunc() {
    try(Formatter fmt = new Formatter()) { // Formatter should also be properly closed
    for(int i=1; i<=10; i++) {
    fmt.format("%4d", i);
    }
    System.out.println(fmt);
    }
    }
  2. 每次使用新的Formatter

    static void formatterFunc() {
    String myString = "";
    for(int i=1; i<=10; i++) {
    myString = myString + new Formatter().format("%4d", i); // But needs closing strictly speaking
    }
    System.out.println(myString);
    }
  3. 提供您自己的Appendable

    static void formatterFunc() {
    StringBuilder sb = new StringBuilder();
    try(Formatter fmt = new Formatter(sb)) { // Formatter should be properly closed
    for(int i=1; i<=10; i++) {
    fmt.format("%4d", i);
    }
    }
    System.out.println(sb.toString()); // We can print this even after Formatter has been closed
    }

关于Java 的格式说明符重复打印输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37164788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com