【问题标题】:java formatting tabular outputjava格式化表格输出
【发布时间】:2017-03-27 01:00:51
【问题描述】:

所以我正在尝试格式化我的输出

System.out.println("Menu:\nItem#\tItem\t\tPrice\tQuantity");
    for(int i=0;i<stock.length;i++){
        System.out.println((i+1)+"\t"+stock[i].Description + "\t\t"+stock[i].price + "\t"+stock[i].quantity);

the output should be like

but it comes out as

【问题讨论】:

  • 我建议对 printf 和 String#format 进行一些研究
  • 不要指望制表符来正确格式化内容。曾经。只是不要使用它们。

标签: java format


【解决方案1】:

Java 有一种使用System.out.format 打印表格的好方法

这是一个例子:

Object[][] table = new String[4][];
table[0] = new String[] { "Pie", "2.2", "12" };
table[1] = new String[] { "Cracker", "4", "15" };
table[2] = new String[] { "Pop tarts", "1", "4" };
table[3] = new String[] { "Sun Chips", "5", "2" };

System.out.format("%-15s%-15s%-15s%-15s\n", "Item#", "Item", "Price", "Quantity");
for (int i = 0; i < table.length; i++) {
    Object[] row = table[i];
    System.out.format("%-15d%-15s%-15s%-15s\n", i, row[0], row[1], row[2]);
}

结果:

Item#          Item           Price          Quantity       
0              Pie            2.2            12             
1              Cracker        4              15             
2              Pop tarts      1              4              
3              Sun Chips      5              2              

【讨论】:

  • System.out.prinf & System.out.format 实际上是一回事!如this question所示。
  • 哦,好吧,我终于做到了System.out.printf("Menu:\n%-10s %-10s %12s %14s\n","Item#","Item","Price","Quantity"); for(int i=0;i&lt;stock.length;i++){ System.out.printf("%-10d %-10s %11.2f %8d\n",(i+1),stock[i].Description, stock[i].price, stock[i].quantity);
  • 如果我也需要表格边框怎么办?列之间垂直|
猜你喜欢
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多