Dynamic Formatting
A Programming Pattern |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
String
objects and
generate formatted outputString
operations/methodsfor (int i = 0; i < data.length; i++) { System.out.printf("%10d\n", data[i]); }
However, suppose, instead, that you want the field to be as narrow as possible.
String
fs = "%10d\n"; for (int i = 0; i < data.length; i++) { System.out.printf(fs, data[i]); }
fs = "%"; if (flags != null) fs += flags; if (width > 0) fs += width; if (precision > 0) fs += "." + precision; fs += conversion;
String
/** * Use dynamic formatting to center a String in a field of a given width. * * @param source The String to center * @param width The width of the resulting String * @return The centered String */ public static String center(String source, int width) { int field, n, append; String fs, result; // Calculate the number of spaces in the resulting String n = width - source.length(); if (n <= 0) return source; // Calculate the width of the field for source (it will be // right-justified in this field) field = (width + source.length()) / 2; // Calculate the number of spaces to append to the right append = width - field; // Build the format specifier fs = "%" + field + "s%" + append + "s"; result = String.format(fs, source, " "); return result; }