按列打印 Java 数组

2022-01-15 00:00:00 arrays format java

我正在尝试在 Java 中格式化两个数组以打印如下内容:

I'm trying to format two arrays in Java to print something like this:

Inventory Number      Books                          Prices
------------------------------------------------------------------
1                     Intro to Java                  $45.99
2                     Intro to C++                   $89.34
3                     Design Patterns                $100.00
4                     Perl                           $25.00

我正在使用以下代码:

for(int i = 0; i < 4; i++) {
        System.out.print(i+1);
        System.out.print("                     " + books[i] + " ");
        System.out.print("                 " + "$" + booksPrices[i] + " ");
        System.out.print("
");
    }

但是我得到了这个格式很差的结果:

But I am getting this poorly formatted result instead:

Inventory Number      Books                          Prices
------------------------------------------------------------------
1                     Intro to Java                  $45.99 
2                     Intro to C++                  $89.34 
3                     Design Patterns                  $100.0 
4                     Perl                  $25.0 

如何将所有列直接排列在顶部标题下方?

How would I go about lining all the columns up directly under the headers at the top?

有没有更好的方法来做到这一点?

Is there a better way to go about doing this?

推荐答案

你应该看看格式:

System.out.format("%15.2f", booksPrices[i]);   

这将提供 15 个插槽,并在需要时用空格填充它.

which would give 15 slots, and pad it with spaces if needed.

但是,我注意到您没有右对齐您的数字,在这种情况下,您希望在书籍字段中左对齐:

However, I noticed that you're not right-justifying your numbers, in which case you want left justification on the books field:

System.out.printf("%-30s", books[i]);

这是一个工作片段示例:

Here's a working snippet example:

String books[] = {"This", "That", "The Other Longer One", "Fourth One"};
double booksPrices[] = {45.99, 89.34, 12.23, 1000.3};
System.out.printf("%-20s%-30s%s%n", "Inventory Number", "Books", "Prices");
for (int i=0;i<books.length;i++){
    System.out.format("%-20d%-30s$%.2f%n", i, books[i], booksPrices[i]);
}

导致:

Inventory Number    Books                         Prices
0                   This                          $45.99
1                   That                          $89.34
2                   The Other Longer One          $12.23
3                   Fourth One                    $1000.30

相关文章