- Forward


Dynamic Formatting
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Background:
    • You have experience with using format specifiers to create formatted String objects and generate formatted output
  • A Limitation:
    • You've always created the format specifier at "compile time"
  • Overcoming this Limitation:
    • Create the format specifier at "run time" using various String operations/methods
Motivation (cont.)
Back SMYC Forward
Printing All of the Elements of an Array in a Field of Width 10
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: hardcodedsimple)
 

However, suppose, instead, that you want the field to be as narrow as possible.

Review
Back SMYC Forward
  • Finding the Largest Element:
    • Use an accumulator
  • Finding the Number of Digits in the Largest Element:
    • Use digit counting
  • What's Left?
    • Creating a format specifier
Thinking About the Problem
Back SMYC Forward
  • Some Observations:
    • The format specifier is a String
    • Though we commonly use a literal, a variable could be used
  • Returning to the Example:
    • javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: hardcodedvariable)
       
The Pattern
Back SMYC Forward
  • Recall the Syntax of Format Specifiers:
    • %[flags][width][.precision]conversion
  • Dynamic Construction:
    • javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: pattern)
       
Examples
Back SMYC Forward
Print a Table Containing the Digits of \(\pi\)
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: pi)
 
Examples (cont.)
Back SMYC Forward
Centering Text in a String
javaexamples/programmingpatterns/DynamicFormatting.java (Fragment: center)
 
There's Always More to Learn
Back -