0

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?

1
  • Hi, try using the \t. Eg.: System.out.println(String.format("\t %s", books[i]); And for a double tab, use \t\t and so on as many as you want Commented Oct 30, 2015 at 19:40

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

That's actually better than what I wrote in comments. +1
2

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.

1 Comment

Prepending a "-" aligns to the left.
0

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;
}

1 Comment

Or, instead of appending the whitespace characters manually, you can also use String.format, as @ergonaut showed in his answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.