JMU
Dynamic Formatting
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Motivation (cont.)
Printing All of the Elements of an Array in a Field of Width 10
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: hardcodedsimple)
                for (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.

Review
Thinking About the Problem
The Pattern
Examples
Print a Table Containing the Digits of \(\pi\)
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: pi)
                for (int digits = 1; digits <= 10; digits++) {
            fs = "%" + (digits + 2) + "." + digits + "f\n";
            System.out.printf(fs, Math.PI);
        }
        
Examples (cont.)
Centering Text in a String
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: center)
            /**
     * 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;
    }