美元符号 ($) 在 printf 格式字符串中起什么作用?

What does the dollar sign ($) do in a printf format string?

我正在尝试使用此网页中的 printf 语句在 java 中进行格式化:Click Here。但我就是想不通 $ 符号的用途是什么。有人可以给我解释一下吗?

输入:

java 100
cpp 65
python 50

预期输出:(应该有一个 space 而不是 _ )

 ================================
 java___________100 
 cpp___________065 
 python_________050 
 ================================

我的代码:

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("================================");
        for(int i=0;i<3;i++)
        {
            String s1=sc.next();
            int x=sc.nextInt();
            System.out.printf(s1 + "%03d", x);
            System.out.println();
        }
        System.out.println("================================");

    }
}

这是参数索引You can read the docs。我将尝试为您解释教程中的字符串:

String fmt = "%1s %2s %3s%n";

// format
cnsl.printft(fmt, "Items", "Quantity", "Price");
cnsl.printft(fmt, "-----", "-----", "-----");
cnsl.printft(fmt, "Tomato", "1 kg", "15");
cnsl.printft(fmt, "Potato", "5 kg", "50");
cnsl.printft(fmt, "Onion", "2 kg", "30");
cnsl.printft(fmt, "Apple", "4 kg", "80");

一般格式为%[argument_index$][flags][width][.precision]conversion

在我们的示例中,#$ 指向我们的 printft() 语句中的位置。我们有 3 个字符串需要格式化,因此我们的格式字符串有 1$2$3$。每个参数之间的宽度后面的数字。此宽度从 0 开始,这意味着实际宽度为 +1。 s 是我们对字符串的转换,最后是 %n 新行。

Items      Quantity      Price
-----      --------      -----
Tomato     1 kg          15
Potato     5 kg          50
Onion      2 kg          30
Apple      4 kg          80