2013-09-07 16 views
7

私はJavaでテーブルを印刷しようとしていますが、これを行うにはどうすればよいのでしょうか?Javaで情報テーブルを印刷するには

私は新しい行を印刷しようとしましたが、\ tを使用して内容の行を修正しようとしましたが、動作しません。これまたはより良い方法を行う方法はありますか?

+0

は、整列した文字列の書式を見てください。 –

答えて

10

あなたは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); 
+0

任意の数の要素に対してこれを行うことは可能ですか? – corvid

+0

申し訳ありませんが、私はあなたの質問を理解していません。あなたはそれをより良く説明できますか? –

+0

これよりもむしろ左を向く道がありますか? –

1

文字列を希望の列長にスペースで埋め込む関数を記述します。これは静的ヘルパーにすることができ、クラスStrUtilsなどを作成して保持することができます。あなたは表形式のデータを出力している場合

(もあなたのためにこれを行うには文字列ヘルパー/ utilsパッケージとApacheや他のライブラリがあるかもしれません。)

長期的には、(エクセルなどのために)CSVのエクスポートを検討することもできまたはXML。しかし、これは典型的な長期的なビジネス要件のためのもので、すぐに画面に出力するだけではありません。

+0

ご協力ありがとうございます。私はいくつかの文字列関数を見ていきます – user2704743

1

これは1つです

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

}

出力:それ実行する方法

enter image description here

関連する問題