我正在尝试使用 printf 语句在 java 中进行格式化,如本网页所示:Click Here 。但我就是不明白 $ 符号的用途是什么。有人可以向我解释一下吗?
输入:
java 100
cpp 65
python 50
预期输出:(应该有一个空格而不是 _ )
================================
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 = "%1$4s %2$10s %3$10s%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
关于java - 美元符号 ($) 在 printf 格式字符串中起什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458695/