[英]How to print a table of information in Java
我正在嘗試在 Java 中打印一張表格,我想知道最好的方法是什么?
我嘗試打印新行並使用 \t 使內容對齊,但它不起作用。 有沒有一種方法可以做到這一點或更好的方法?
您可以使用 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 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
這是一種方法:
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);
}
}
輸出:
編寫一個函數,用空格將字符串填充到所需的列長度。 這可以是一個靜態幫助器,您可以創建一個 StrUtils 類或類似的類來保存它。
(也可能有 Apache 或其他帶有 String helpers/utils 的庫可以為您執行此操作。)
長期來看,如果您要輸出表格數據,您可以考慮導出 CSV(用於 Excel 等)或 XML。 但這些是針對典型的長期業務需求,而不僅僅是快速的屏幕輸出。
我認為使用J-Text-Utils為您輸出表格將是一種方便的方法。 通過這個小型庫,您無需重新發明輪子。 您只需輸入您的數據,它就會為您處理格式。
這是來自他們的Google Code 網站的示例:
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();
輸出:
有一個帶有 Markdown 格式打印表格功能的小庫: https : //github.com/mjfryc/mjaron-etudes-java
Iterable
。public String something;
要么public String getSomething();
要么
public boolean hasSomething();
import pl.mjaron.etudes.Obj;
...
List<Cat> cats = Arrays.asList(cat0, cat1);
String table = Obj.asTable(cats, Cat.class);
示例輸出:
| name | legsCount | lazy | topSpeed |
| ---- | --------- | ----- | -------- |
| John | 4 | true | 35.24 |
| Bob | 5 | false | 75.0 |
PS我是這個圖書館的作者,享受。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.