【问题标题】:Formatting spaces between two listed arrays [duplicate]格式化两个列出的数组之间的空格[重复]
【发布时间】:2022-01-17 06:53:52
【问题描述】:

我怎样才能格式化这个输出的表格是内联的并且空格是相等的?

public class jh {

public static void main(String[] args) {
    
    int [] quantity = {31, 10, 30, 19, 25, 80}; 
    
    String [] product = {"Milk", "Eggs", "Cereal", "Apples", "Cheese","Chicken"}; 
    
    System.out.println("Index  Product    Quantity");
    for (int i=0; i<6;i++)
    { 
    System.out.println(i+1+"  "+product [i]+"  "+quantity[i]); 
    
    
}

}
}

【问题讨论】:

  • 为什么不能使用printf

标签: java arrays for-loop printf


【解决方案1】:

您可以使用System.out.formatString.format 指定每个元素的宽度。

System.out.println("Index  Product    Quantity");
for (int i = 0; i < 6; i++) { 
    System.out.format("%-6s %-10s %-8s%n", i + 1, product[i], quantity[i]); 
}

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2019-09-15
    • 2016-04-16
    • 1970-01-01
    • 2015-07-18
    • 2020-06-12
    相关资源
    最近更新 更多