gpt4 book ai didi

Java:使用 Printf 对齐代码?

转载 作者:行者123 更新时间:2023-11-30 11:18:17 31 4
gpt4 key购买 nike

Java 中使用 Printf 时,您如何知道要使用什么“-10”、“-20”等来格式化 你的输出尽可能可读。例如。在以下代码中:

System.out.printf("[%-10s] %-20s %-20s £%.2f","Employee",this.firstName, this.lastName, this.baseRate);

对于要使用的数字是否有固定的公式等?

最佳答案

是的,有可用的文档描述每个格式选项的用途:Java printf quick reference

总结(从链接文档中复制):

格式字符串:

由文字和格式说明符组成。仅当格式字符串中有格式说明符时才需要参数。格式说明符包括:标志、宽度、精度和按以下顺序转换字符:

%[flags][width][.precision]conversion-character

(方括号表示可选参数)

标志:

- : left-justify (default is to right-justify)
+ : output a plus (+) or minus (-) sign for a numerical value
0 : forces numerical values to be zero-padded ( default is blank padding )
, : comma grouping separator (for numbers > 1000)
: space will display a minus sign if the number is negative or a space if it is positive

宽度:

指定输出参数的字段宽度,表示要写入输出的最少字符数。在预期的逗号和小数点中包含空格确定数值的宽度。

精度:

用于根据转换限制输出。它指定输出浮点值时的精度位数或要从 String 中提取的子字符串的长度。数字四舍五入到指定的精度。

转换字符:

d : decimal integer [byte, short, int, long]
f : floating-point number [float, double]
c : character Capital C will upper case the letter
s : String Capital S will uppercase all the letters in the string
h : hashcode A hashcode is like an address. This is useful for printing a reference
n : newline Platform specific newline character - use %n instead of \n for greater compatibility

关于Java:使用 Printf 对齐代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23901037/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com