Print Java arrays in columns

后端 未结 3 1902
梦如初夏
梦如初夏 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:36

    You can use

    System.out.printf(...)
    

    for formatting the output. That uses

    String.format(...)
    

    which uses

    java.util.Formatter
    

    you can find the documentation here.

    To align a simple String, you can use the following:

    String formatted = String.format("%20s", str)
    

    this will prepend

    20 - str.length
    

    blanks before the actual String and will return the padded String. For example, if your String is "Hello, World!" it will prepend 11 blanks:

    "           Hello, World!"
    

    to align something to the right left, you have to prepend a "-" before the number that indicates the length of the result string.

    To safely align everything, you first have to find out what is your longest string.

提交回复
热议问题