Java 中的参数索引


参数索引允许程序员重新排序输出。来看一个例子。

例子

 在线示例

public class Demo {
   public static void main(String[] args) {
      System.out.printf("Before reordering = %s %s %s %s %s %s
", "one", "two", "three", "four", "five", "six" );       System.out.printf("After reordering = %6$s %5$s %4$s %3$s %2$s %1$s
","one", "two", "three", "four", "five", "six" );       System.out.printf("Before reordering = %d %d %d
", 100, 200, 300);       System.out.printf("After reordering = %2$d %3$d %1$d
", 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
", 100, 200, 300);

但是,我们改变了顺序,并将其显示为 -

System.out.printf("After reordering = %2$d %3$d %1$d
", 100, 200, 300);

更新时间:2020 年 6 月 27 日

510 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告