“%1$d”在格式字符串中是什么意思?

What does "%1$d" mean in a format string?

我不明白这个 %1$d 格式说明符是什么意思。有人可以帮助我吗?

int zahl = 100;
System.out.format("A number: %1$d %n", zahl);

x$ 表示参数编号 x.

以下将打印Hello World:

System.out.printf("%s %s", "Hello", "World");

下面两个都将打印 World Hello:

System.out.printf("%2$s %1$s", "Hello", "World");
System.out.printf("%s %s", "World", "Hello");

来自https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

The format specifiers for general, character, and numerical types have the following syntax: %[argument_index$][flags][width][.precision]conversion

1$ 代表您的第一个参数,即您的 zahl 变量。 %d 是整数的格式说明符。 $ 约定用于避免多次重复使用您的参数。一个例子是,

Date date = new Date();
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);

在上面的打印语句中,您可以通过以下方式代替多次传递日期变量,

System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);