在列中打印Java数组 [英] Print Java arrays in columns

查看:128
本文介绍了在列中打印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("\n");
    }

但我得到了这个格式错误的结果:

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

这篇关于在列中打印Java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆