如何在Java中打印信息表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18672643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:04:45  来源:igfitidea点击:

How to print a table of information in Java

javatext-alignment

提问by user2704743

I'm trying to print a table in Java and I was wondering what is the best way to do this?

我正在尝试用 Java 打印一个表格,我想知道这样做的最佳方法是什么?

I've tried printing new lines and using \t to make contents line up but it doesn't work. Is there a method which does this or a better way?

我试过打印新行并使用 \t 使内容对齐,但它不起作用。有没有一种方法可以做到这一点或更好的方法?

采纳答案by Luca Mastrostefano

You can use System.out.format(...)

您可以使用 System.out.format(...)

Example:

例子:

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);
}

Result:

结果:

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

Or use the following code for left-aligned output:

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

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

回答by Thomas W

Write a function which pads a string to your desired column-length with spaces. This can be a static helper, and you can create a class StrUtils or similar to hold it.

编写一个函数,用空格将字符串填充到所需的列长度。这可以是一个静态帮助器,您可以创建一个 StrUtils 类或类似的类来保存它。

(There may also be Apache or other libraries with String helpers/utils to do this for you.)

(也可能有 Apache 或其他带有 String helpers/utils 的库可以为您执行此操作。)

Long-term, if you're outputting tabular data you could consider exporting CSV (for Excel etc) or XML. But these are for typical long-term business requirements, not just a quick to-screen output.

长期来看,如果您要输出表格数据,您可以考虑导出 CSV(用于 Excel 等)或 XML。但这些是针对典型的长期业务需求,而不仅仅是快速的屏幕输出。

回答by Ojonugwa Jude Ochalifu

This is one way to do it:

这是一种方法:

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);
 }

}

}

Output:

输出:

enter image description here

在此处输入图片说明

回答by Vadim Zverev

General function to table-format a list of arrays:

对数组列表进行表格格式化的通用函数:

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();
}

Usage:

用法:

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));

The result:

结果:

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