1

我有一堆数据需要美化和输出。我正在使用的当前代码是:

String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", string, int, int, int);

我的第一个文件的结果输出是:

2006-09-16 09:00:01      1                0               501
2006-09-16 08:15:00      0                4               401
2006-09-15 07:05:15      0                3               301

字符串始终是那个长度,但问题在于接下来的两个整数,因为它们的长度可以是 1 或 2。

当我使用我的其他文件时,我得到:

2006-09-29 00:01:01     36               19               600
2006-09-30 21:00:00     9               33               599
2006-09-28 05:16:00     15               6               599

后两行向左移动 1 个空格。是否有可能使无论整数的长度如何,它们总是出现在同一个地方,从而消除发生的移位因子?

4

1 回答 1

0

在 Eclipse 中尝试了这段代码:

public class StringFormatting
{
    public static void main(String[] args) 
    {         
         System.out.println(String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", "2006-09-29 00:01:01", 36, 19, 600));
         System.out.println(String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", "2006-09-30 21:00:00", 9, 33, 599));
         System.out.println(String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", "2006-09-29 00:01:01", 15, 6, 600));
         System.out.println(String.format("%1s" + "%7d" + "%17d" + "%18d" + "\n", "2006-09-29 00:01:01", 36, 19, 600));
    }
}

我得到了正确对齐的格式输出:

2006-09-29 00:01:01     36               19               600

2006-09-30 21:00:00      9               33               599

2006-09-29 00:01:01     15                6               600

2006-09-29 00:01:01     36               19               600

也许是 Eclipse 控制台窗口在这里做正确的工作。打败我...

于 2010-07-11T02:31:06.350 回答