I'm pretty new to Java so be gentle, please.

I'm trying to set up a columnar structure to output to the console with tabs in between each column. However, I want some of the tabs to be right aligned, not left. As you can see below, I'm using a String.format() method and System.out.print(). Any suggestions?

output += String.format("%d\t\t%.2f\t\t%.2f\t\t%.2f\n", i, interest, principal, balance);

I swore there was some sort of text justifiers added in 1.5 but I can't seem to find what they were.

It's really not hard to create your own method to pad and align text.

public static String padAlign(String string, int fieldLength, char padding, boolean alignRight)
        int length = fieldLength - string.length();
        if (length <= 0)
            return string.substring(0,string.length());
        StringBuffer buffer = new StringBuffer(fieldLength);
        for(int i=0; i<length; i++)
        if (alignRight)
        return new String(buffer);    
    public static void main(String[] args)
        System.out.println(padAlign("Test",20,' ',true)+" "+padAlign("Test again",20,' ',true));
        System.out.println(padAlign("Test",20,' ',false)+" "+padAlign("Test again",20,' ',false));

Thank you for your help. Unfortunately, I am still a newbie and I didn't really understand how to implement the suggested solutions. I haven't learned much about classes or packages yet. :-|

However, I was able to solve the problem on my own with a slight modification to my code as seen here.

output += String.format ("%-10d%10.2f%15.2f%15.2f\n",  i, interest, principal, balance);

This aligned my columns perfectly. Thanks again for the suggestions! :p

This article has been dead for over six months. Start a new discussion instead.