Formatted "Pretty" print in Java

Steve Jennings
Steve Jennings used Ask the Experts™
on
I print a few lines of text as a result of a query.

office    3238 0 299939

Column 1 is always the office and is an 11-character string, 2 is the number of "gapped" calls, col 3 is "blocked" and col 4 is "deflected". How can I right justify the fields? How can I start the rightmost character of each field in the same column? Columns 2 and 3 will never be larger than 7 digits. and column 4 could be up to 10 digits.

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mick BarryJava Developer
Top Expert 2010

Commented:
Look at ChoiceFormat, DataFormat, NumberFormat, and TimeFormat classes.

Of the following gives printf like functionality if you are familiar with that:
http://www.acme.com/java/software/Acme.Fmt.html
Top Expert 2006
Commented:
You just want to print that with a fixed-width font and use spaces to align the fields?
Choose the final length you want and add spaces in front or at the end of your string.

example for final length = 12:

String strField = "xyz";
String padding = "            ";  // 12 spaces.

String leftJustified = (strField + padding).substring(0,12);

String strPadded = padding + strField;
String rightJustified = strPadded.substring(strPadded.length -13);
Top Expert 2006

Commented:
You can also use a loop that adds one space in front or at the end of your string.
Do you have each column in a separate string variable or do you have one long string variable that contains the 4 columns?
Top Expert 2016
Commented:
This is one way of doing it:

import java.util.Arrays;

public class PrintJustified {

  public static int GAP = 1;
  public static int COL1_LENGTH = 11 + GAP;
  public static int COL2_LENGTH = 7 + GAP;
  public static int COL3_LENGTH = 7 + GAP;
  public static int COL4_LENGTH = 10 + GAP;

  public static char[] OFFICE = new char[COL1_LENGTH];
  public static char[] GAPPED = new char[COL2_LENGTH];
  public static char[] BLOCKED = new char[COL3_LENGTH];
  public static char[] DEFLECTED = new char[COL4_LENGTH];


  public static void print(String office, String gapped, String blocked, String deflected) throws ArrayIndexOutOfBoundsException {
    if (office.length() > OFFICE.length ||
      gapped.length() > GAPPED.length ||
      blocked.length() > BLOCKED.length ||
      deflected.length() > DEFLECTED.length)
        throw new ArrayIndexOutOfBoundsException("One or more fields too long to print");
    clearArrays();
    char[] officeChars = office.toCharArray();
    for(int i = 0;i < officeChars.length;i++) {
      OFFICE[i] = officeChars[i];
    }
    int fieldIndex = GAPPED.length - 1;
    char[] gappedChars = gapped.toCharArray();
    for(int i = gappedChars.length - 1;i >= 0;i--) {
      GAPPED[fieldIndex] = gappedChars[i];
      fieldIndex--;
    }
    fieldIndex = BLOCKED.length - 1;
    char[] blockedChars = blocked.toCharArray();
    for(int i = blockedChars.length - 1;i >= 0;i--) {
      BLOCKED[fieldIndex] = blockedChars[i];
      fieldIndex--;
    }
    fieldIndex = DEFLECTED.length - 1;
    char[] deflectedChars = deflected.toCharArray();
    for(int i = deflectedChars.length - 1;i >= 0;i--) {
      DEFLECTED[fieldIndex] = deflectedChars[i];
      fieldIndex--;
    }
    System.out.print(OFFICE);
    System.out.print(GAPPED);
    System.out.print(BLOCKED);
    System.out.println(DEFLECTED);
  }

  static void clearArrays() {
    Arrays.fill(OFFICE, ' ');
    Arrays.fill(GAPPED, ' ');
    Arrays.fill(BLOCKED, ' ');
    Arrays.fill(DEFLECTED, ' ');
  }


  public static void main(String[] args) {
    // For testing purposes
    String[][] data = {
      { "office", "28", "98457", "9487593874" },
      { "subsidiary", "4736", "3948", "32948" },
      { "main", "438975", "324", "309485908" }
    };
    try {
      for(int i = 0;i < data.length;i++) {
        print(data[i][0], data[i][1], data[i][2], data[i][3]);
      }
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

}

Commented:
Example method that you could call....

  /**
   * Prints data in fixed columns.  Data will be truncated or padded to fit
   * @param columns The number of columns to use for display
   * @param data The data
   * @param leftJustified
   */  
  private void print(int columns, String data, boolean leftJustified) {
    if (data == null) {
      data = "";
    }
    if (data.length() > columns) {
      data = data.substring(0, columns);
    }
    if (leftJustified) {
      writer.print(data);
    }
    for (int i=0; i<columns-data.length(); i++) {
      writer.print(' ');
    }
    if (!leftJustified) {
      writer.print(data);
    }
  }

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial