且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 system.out.printf 格式化 java 字符串

更新时间:2023-11-10 09:10:46

字段宽度说明符不是间距说明.

The field width specifiers are not spacing specs.

%-1 表示在字段中左对齐至少一个字符宽.但是您的第一列始终至少有 3 个字符宽,因此会忽略说明符.纯粹出于巧合,第一列看起来很整齐:您的所有数字碰巧都是三位数.

%-1 means left align in a field at least one character wide. But your first column is always at least 3 characters wide, so the specifier is ignored. The first column comes out looking neat purely by coincidence: all your numbers happen to have three digits.

同样,%10 表示在至少 10 个字符宽的字段中右对齐.但是您所有的相机名称都比这长得多,因此实际上忽略了说明符.

Similarly, %10 means right align in a field at least 10 characters wide. But all your camera names are much longer than that, so the specifier is effectively ignored.

您可能正在寻找更像的东西

You are probably looking for something more like

%-4s%-25s%6.2f

这意味着:

  1. 左对齐字段中的第一个参数,宽度至少为 4 个字符
  2. 在至少 25 个字符宽的字段中左对齐第二个参数
  3. 在至少 6 个字符宽的字段中打印右对齐的数字,小数点后保留两位数

您可以将 %4s 替换为 %3s 以获得类似的效果.不同之处在于溢出的处理方式.第一个版本在第一列中长度超过 3 个字符的值后面没有空格.第二个会.

You could replace %4s with %3s<space> for a similar effect. The difference would be in how overflow is handled. The first version would not have a space following values in the first column that were longer than 3 characters. The second one would.