如何在Java中打印信息表

1tuwyuhd  于 2023-01-29  发布在  Java
关注(0)|答案(6)|浏览(198)

我正在尝试用Java打印一个表,我想知道什么是最好的方法来做到这一点?
我试过打印新行并使用\t使内容排成一行,但是不起作用。有没有这样的方法或更好的方法?

ivqmmu1c

ivqmmu1c1#

您可以使用System.out.format(...)
示例:

final Object[][] table = new String[4][];
table[0] = new String[] { "foo", "bar", "baz" };
table[1] = new String[] { "bar2", "foo2", "baz2" };
table[2] = new String[] { "baz3", "bar3", "foo3" };
table[3] = new String[] { "foo4", "bar4", "baz4" };

for (final Object[] row : table) {
    System.out.format("%15s%15s%15s%n", row);
}

结果:

foo            bar            baz
       bar2           foo2           baz2
       baz3           bar3           foo3
       foo4           bar4           baz4

或者使用以下代码进行左对齐输出:

System.out.format("%-15s%-15s%-15s%n", row);
1u4esq0p

1u4esq0p2#

用于将数组列表设置为表格格式的常规函数:

public static String formatAsTable(List<List<String>> rows)
{
    int[] maxLengths = new int[rows.get(0).size()];
    for (List<String> row : rows)
    {
        for (int i = 0; i < row.size(); i++)
        {
            maxLengths[i] = Math.max(maxLengths[i], row.get(i).length());
        }
    }

    StringBuilder formatBuilder = new StringBuilder();
    for (int maxLength : maxLengths)
    {
        formatBuilder.append("%-").append(maxLength + 2).append("s");
    }
    String format = formatBuilder.toString();

    StringBuilder result = new StringBuilder();
    for (List<String> row : rows)
    {
        result.append(String.format(format, row.toArray(new String[0]))).append("\n");
    }
    return result.toString();
}

用法:

List<List<String>> rows = new ArrayList<>();
List<String> headers = Arrays.asList("Database", "Maintainer", "First public release date", "Latest stable version", "Latest release date");
rows.add(headers);
rows.add(Arrays.asList("4D (4th Dimension)", "4D S.A.S.", "1984", "v16.0", "2017-01-10"));
rows.add(Arrays.asList("ADABAS", "Software AG", "1970", "8.1", "2013-06"));
rows.add(Arrays.asList("Adaptive Server Enterprise", "SAP AG", "1987", "16.0", "2015"));
rows.add(Arrays.asList("Apache Derby", "Apache", "2004", "10.14.1.0", "2017-10-22"));

System.out.println(formatAsTable(rows));

结果是:

Database                    Maintainer   First public release date  Latest stable version  Latest release date  
4D (4th Dimension)          4D S.A.S.    1984                       v16.0                  2017-01-10           
ADABAS                      Software AG  1970                       8.1                    2013-06              
Adaptive Server Enterprise  SAP AG       1987                       16.0                   2015                 
Apache Derby                Apache       2004                       10.14.1.0              2017-10-22
xzv2uavs

xzv2uavs3#

这是一种方法:

public class StoreItem {

    private String itemName;
    private double price;
    private int quantity;

    public StoreItem(String itemName, double price, int quantity) {
        this.setItemName(itemName);
        this.setPrice(price);
        this.setQuantity(quantity);
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public static void printInvoiceHeader() {
        System.out.println(String.format("%30s %25s %10s %25s %10s", "Item", "|", "Price($)", "|", "Qty"));
        System.out.println(String.format("%s", "----------------------------------------------------------------------------------------------------------------"));
    }
    public void printInvoice() {
        System.out.println(String.format("%30s %25s %10.2f %25s %10s", this.getItemName(), "|", this.getPrice(), "|", this.getQuantity()));
    }

    public static List<StoreItem> buildInvoice() {
        List<StoreItem> itemList = new ArrayList<>();
        itemList.add(new StoreItem("Nestle Decaff Coffee", 759.99, 2));
        itemList.add(new StoreItem("Brown's Soft Tissue Paper", 15.80, 2));
        itemList.add(new StoreItem("LG 500Mb External Drive", 700.00, 2));
        return itemList;
    }

    public static void main (String[] args) {

        StoreItem.printInvoiceHeader();
        StoreItem.buildInvoice().forEach(StoreItem::printInvoice);
     }
}

输出:

hvvq6cgz

hvvq6cgz4#

编写一个函数,用空格将一个字符串填充到你想要的列长。这可以是一个静态帮助器,你可以创建一个类StrUtils或类似的类来保存它。
(也可能有Apache或其他带有String helpers/utils的库可以为您完成此操作。
从长远来看,如果你输出表格数据,你可以考虑导出CSV(Excel等)或XML。但这些都是典型的长期业务需求,而不仅仅是一个快速到屏幕输出。

soat7uwm

soat7uwm5#

我认为使用J-Text-Utils来输出表格是一种很方便的方法,通过这个小库,你不需要重新发明轮子,你只需要输入你的数据,它会为你处理格式。
这是Google Code site的一个示例:

String[] columnNames = {
"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};

Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)}, {"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};

TextTable tt = new TextTable(columnNames, data);
// this adds the numbering on the left
tt.setAddRowNumbering(true);
// sort by the first column
tt.setSort(0);
tt.printTable();

输出:

fxnxkyjh

fxnxkyjh6#

使用反射将Java对象打印为Markdown表的库:https://github.com/mjfryc/mjaron-etudes-java

dependencies {
  implementation 'io.github.mjfryc:mjaron-etudes-java:0.1.12'
}
import pl.mjaron.etudes;

class Sample {
    void sample() {
        List<Cat> cats = Arrays.asList(cat0, cat1);
        String table = Table.render(cats, Cat.class);
        System.out.println(table);
    }
}

样本输出:

| name | legsCount |  lazy | topSpeed |
| ---- | --------- | ----- | -------- |
| John |         4 |  true |    35.24 |
|  Bob |         5 | false |     75.0 |

相关问题