java formatting tabular output

我怕爱的太早我们不能终老 提交于 2021-01-24 13:58:15

问题


so i'm trying to format my output

System.out.println("Menu:\nItem#\tItem\t\tPrice\tQuantity");
    for(int i=0;i<stock.length;i++){
        System.out.println((i+1)+"\t"+stock[i].Description + "\t\t"+stock[i].price + "\t"+stock[i].quantity);

the output should be like

but it comes out as


回答1:


Java has a nice happy way to print out tables using System.out.format

Here's an example:

Object[][] table = new String[4][];
table[0] = new String[] { "Pie", "2.2", "12" };
table[1] = new String[] { "Cracker", "4", "15" };
table[2] = new String[] { "Pop tarts", "1", "4" };
table[3] = new String[] { "Sun Chips", "5", "2" };

System.out.format("%-15s%-15s%-15s%-15s\n", "Item#", "Item", "Price", "Quantity");
for (int i = 0; i < table.length; i++) {
    Object[] row = table[i];
    System.out.format("%-15d%-15s%-15s%-15s\n", i, row[0], row[1], row[2]);
}

Results:

Item#          Item           Price          Quantity       
0              Pie            2.2            12             
1              Cracker        4              15             
2              Pop tarts      1              4              
3              Sun Chips      5              2              


来源:https://stackoverflow.com/questions/43036396/java-formatting-tabular-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!