简体   繁体   English

java格式表格输出

[英]java formatting tabular output

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 但它出来了

Java has a nice happy way to print out tables using System.out.format Java有一种很好的方式来使用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              

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM