How to Format Columns in Java

How to Format Columns in Java thumbnail
Your Java code can output columns of aligned field values.

Java code often needs to output tables with rows and columns. Programs generate a table by generating one row at a time. However, in order for the fields in each row to conform to a table format, instances of the same field in different rows must be aligned with each other and with the corresponding column headings. The built-in Java libraries support formatted output. You can write Java code that takes variable-length field values and formats it into neat columns.

Instructions

    • 1

      Include the following lines at the beginning of your Java code:

      import java.io.PrintStream;

      PrintStream myStream = new PrintStream();

      You can use any instance of the PrintStream class to receive the formatted output. In particular, the program's standard output -- System.out -- is an instance of PrintStream.

    • 2

      Format a column entry with an integer value by making it fit into the width of the column, as in the following sample code:

      int myInt = 46;

      myStream.format("%5d",myInt);

      Replace "5" with the width of the column. The example will send " 46" -- the integer value, right-justified by default, preceded by three spaces to occupy five places in total -- to "myStream".

    • 3

      Format a column entry with a floating-point value by making it fit into the width of the column, as in the following sample code:

      float myFloat = 87.494;

      myStream.format("%6.2f",myFloat);

      Replace "6" with the total width of the column -- including the decimal point -- and "2" with the number of decimal places to show. The decimal points will also be lined up over the whole column. The example will send " 87.49" -- the floating-point value, right-justified by default, preceded by a single space to occupy six places in total -- to "myStream".

Tips & Warnings

  • Consult the format specifiers in the documentation for "Java: Class PrintStream" for other possible formats you can use for your columns.

Related Searches:

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images

Comments

Related Ads

Featured