hxs9342
hxs9342

Reputation: 3

Print Java arrays in columns

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

I am using the following code:

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?

Upvotes: 0

Views: 5194

Answers (3)

ergonaut
ergonaut

Reputation: 7057

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<books.length;i++){
    System.out.format("%-20d%-30s$%.2f%n", i, books[i], booksPrices[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

Upvotes: 5

mezzodrinker
mezzodrinker

Reputation: 988

Without using any libraries, you need to determine the maximum length of each coloumn and append the needed space characters appropriately. For example like this:

/**
 * Determines maximum length of all given strings.
 */
public static int maxLength(int padding, String... array) {
    if (array == null) return padding;
    int len = 0;
    for (String s : array) {
        if (s == null) {
            continue;
        }
        len = Math.max(len, s.length());
    }
    return len + padding;
}

/**
 * Unifies array element lengths and appends 3 whitespaces for padding.
 */
public static String[] format(String[] array) {
    if (array == null || array.length == 0) return array;
    int len = maxLength(3, array);
    String[] newArray = new String[array.length];
    for (int i = 0; i < array.length; i++) {
        newArray[i] = array[i];
        while (newArray[i].length() < len) {
            newArray[i] += " ";
        }
    }
    return newArray;
}

Upvotes: 0

Fabian Damken
Fabian Damken

Reputation: 1517

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.

Upvotes: 2

Related Questions