如何用Java打印信息表

如何用Java打印信息表,java,text-alignment,Java,Text Alignment,我正在尝试用Java打印一个表,我想知道最好的方法是什么 我尝试打印新行并使用\t使内容对齐,但不起作用。有没有一种方法可以做到这一点或更好的方法?编写一个函数,用空格将字符串填充到所需的列长度。这可以是一个静态助手,您可以创建一个类StrUtils或类似的类来保存它 (可能还有Apache或其他带有字符串帮助程序/UTIL的库可以为您执行此操作。) 长期而言,如果您输出表格数据,您可以考虑导出CSV(Excel等)或XML。但这些都是为了满足典型的长期业务需求,而不仅仅是快速屏幕输出。您可以使

我正在尝试用Java打印一个表,我想知道最好的方法是什么


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

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

(可能还有Apache或其他带有字符串帮助程序/UTIL的库可以为您执行此操作。)


长期而言,如果您输出表格数据,您可以考虑导出CSV(Excel等)或XML。但这些都是为了满足典型的长期业务需求,而不仅仅是快速屏幕输出。

您可以使用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);

这是一种方法:

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);
 }
公共类存储项{
私有字符串itemName;
私人双价;
私人整数数量;
public StoreItem(字符串itemName、双倍价格、整数数量){
这个.setItemName(itemName);
这个。设定价格(price);
这个。设置数量(数量);
}
公共字符串getItemName(){
返回itemName;
}
public void setItemName(字符串itemName){
this.itemName=itemName;
}
公开双价{
退货价格;
}
公共定价(双倍价格){
这个价格=价格;
}
公共整数getQuantity(){
退货数量;
}
公共无效设置数量(整数数量){
这个。数量=数量;
}
公共静态void printInvoiceHeader(){
System.out.println(字符串格式(“%30s%25s%10s%25s%10s”、“项目”、“价格($)、“|”和“数量”);
System.out.println(String.format(“%s”,“----------------------------------------------------------------------------------------------------------------------------------------”);
}
公共发票(){
System.out.println(String.format(“%30s%25s%10.2f%25s%10s”、this.getItemName()、“|”、this.getPrice()、“|”、this.getQuantity());
}
公共静态列表buildInvoice(){
List itemList=new ArrayList();
添加(新的StoreItem(“雀巢脱咖啡因咖啡”,759.99,2));
添加(新的StoreItem(“布朗软纸巾”,15.80,2));
项目列表。添加(新存储项目(“LG 500Mb外部驱动器”,700.00,2));
返回项目列表;
}
公共静态void main(字符串[]args){
StoreItem.printInvoiceHeader();
StoreItem.buildInvoice().forEach(StoreItem::printInvoice);
}
}

输出:


设置数组列表格式的常规函数:

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

查看对齐的字符串格式。好的,谢谢你的帮助,我将查看一些字符串函数。可以对任意数量的元素执行此操作吗?对不起,科维德,我不理解你的问题。您能更好地解释一下吗?有没有一种方法可以让它向左点而不是向右点?当然,使用System.out.format(“%-15s%-15s%-15s\n”,第行)@corvid-为了在两年后回答您的问题,给出的示例已经展示了如何打印任意数量的表元素。循环的内容是“For
row
表中”
——它一直到找不到下一行
为止,因此您不需要确切知道有多少元素。:)
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