Computer Science Canada

Spacing out text columns

Author:  Alexander [ Thu Oct 08, 2009 3:21 pm ]
Post subject:  Spacing out text columns

I'm looking to space three columns evenly, but just quoting space doesn't work because as the numbers get larger, less space is required to make it even, and it overshoots. So how can I make them line up without having to make a table or anything too complicated?

Java:

//Calculates 30% interest over ten years with $100000
import java.awt.*;
import hsa.Console;
import java.text.DecimalFormat;


public class Assignment10
{
    static Console c;

    public static void main (String[] args)
    {
        c = new Console ();
        DecimalFormat formatter = new DecimalFormat (".00");
        double interest = 0, balance = 100000, int_rate = .3;
        c.println ("YEAR      INTEREST         BALANCE");
        c.println (0 + "         " + 0 + "                " + balance);
        for (int x = 1 ; x < 11 ; x++)
        {
            interest = balance * int_rate;
            balance = balance + interest;
            c.println (x + "         " + formatter.format (interest) + "          " + formatter.format (balance));
        }
    }
}


Author:  seekingKnowledge [ Thu Oct 08, 2009 5:45 pm ]
Post subject:  Re: Spacing out text columns

hi,

rather than using spaces manually, try using tabs...
ie : System.out.println("\t\t\t"); ...... that is for 3 tab spaces... so i suggest trying \t for tabs.... hope that helps

Author:  btiffin [ Thu Oct 08, 2009 5:54 pm ]
Post subject:  Re: Spacing out text columns

Check out http://java.sun.com/developer/technicalArticles/Programming/sprintf/ and the PrintfFormat class. You can set the width of the output field, left or right align etc, etc.

Cheers

Author:  Alexander [ Thu Oct 08, 2009 6:00 pm ]
Post subject:  RE:Spacing out text columns

Thanks a bunch! Problem solved.


: