【问题标题】:String Formatting for a list列表的字符串格式
【发布时间】:2020-03-21 09:54:38
【问题描述】:

我正在使用 CSV 文件中的数据制作购物清单。我在输出格式方面遇到了障碍。我对java不是很熟悉,因为我是编码新手。我想知道是否有人可以告诉我如何将我的标题与下面的信息对齐。现在它的输出是这样的:

Item Category Amount Price Location
Apple Food 12 1 Walmart
Grapes Food 15 0.5 Walmart

我希望它像这样输出:

Item  | Category | Amount | Price | Location
Apple |  Food    |   12   |   1   | Walmart
Grapes|  Food    |   15   |  0.5  | Walmart

到目前为止,我的代码如下所示:

public static void main(String[] args) {
    ArrayList <Caring> csvstuff = new ArrayList <Caring> ();
    String fileName = "Project2.csv";
    File file = new File(fileName);
    try {
        Scanner inputStream = new Scanner(file);
        while (inputStream.hasNext()) {
            String data = inputStream.next();
            String[] values = data.split(",");
            String Item = values[0];
            String Category = values[1];
            String Amount = values[2];
            String Price = values[3];
            String Location = values[4];
            System.out.println(values[0] + " " + values[1] + " " + values[2] + " " + values[3] + " " + values[4]);
            caring _caring = new caring(Item, Category, Amount, Price, Location);
            csvstuff.add(_caring);
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

【问题讨论】:

  • 你研究过如何格式化字符串吗?现在你只是用单个空格分隔符打印出你拥有的东西。
  • 如果你能够使用StringUtils (apache commons) 那么它有在固定宽度内左、中、右对齐的方法。

标签: java output-formatting


【解决方案1】:

您可以为此使用字符串格式。

String format = "%-10s |%10s |%10s |%10s |%10s\n";
System.out.printf(format, values[0], values[1], values[2], values[3], values[4]);

上面的代码会给出预期的结果。

编辑:使用 StringUtils 进行格式化。

String result = StringUtils.EMPTY;
result = StringUtils.center(values[0], 10) + '|' + StringUtils.center(values[1], 10) + '|'+ StringUtils.center(values[2], 15) + '|' + StringUtils.center(values[3], 15) + '|'
+ StringUtils.center(values[4], 15);
System.out.println(result);

【讨论】:

  • 看起来 OP 想要值居中 String.format 不支持居中对齐
  • 谢谢@sprinter 是的 string.format 不支持理由。在这种情况下,我们可以使用 StringUtils。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多