Java中的参数索引
参数索引使程序员可以对输出重新排序。让我们来看一个例子。
示例
public class Demo { public static void main(String[] args) { System.out.printf("Before reordering = %s %s %s %s %s %s\n", "one", "two", "three", "four", "five", "six" ); System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s\n","one", "two", "three", "four", "five", "six" ); System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300); System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300); } }
输出结果
Before reordering = one two three four five six After reordering = six five four three two one Before reordering = 100 200 300 After reordering = 200 300 100
上面,我们已经完全重新排序了输出。订购前,我们正常显示。
System.out.printf("Before reordering = %d %d %d\n", 100, 200, 300);
但是,我们更改了顺序并将其显示为-
System.out.printf("After reordering = %2$d %3$d %1$d\n", 100, 200, 300);