Print Java arrays in columns

后端 未结 3 1880
梦如初夏
梦如初夏 2021-01-16 19:03

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

Inventory Number      Books                          Prices
--------------------------         


        
3条回答
  •  借酒劲吻你
    2021-01-16 19:27

    You should look at format:

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

    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

    resulting in:

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

提交回复
热议问题