Java Reference
In-Depth Information
The starting point for outputting a data value is to create a character representation for it. Once we have
that, we need to extend it to the right to the required field width with spaces. We can implement a
helper method, pad() , in our FormatWriter class that will accept a String object as an argument,
and pad out the string appropriately before returning it:
// Helper method to form string
private String pad(String str) {
if (width == 0) {
return str;
}
int blanks = width - str.length(); // Number of blanks needed
StringBuffer result = new StringBuffer(); // Will hold the output
if(blanks<0) { // Data does not fit
for(int i = 0 ; i<width ; i++)
result.append('X'); // so append X's
return result.toString(); // and return the result
}
if(blanks>0) // If we need some blanks
for(int i = 0 ; i<blanks ; i++)
result.append(' '); // append them
// Insert the value string at the beginning or the end
result.insert(justification == LEFT _ JUSTIFIED ? 0 : result.length(),
str);
return result.toString();
}
We will only use this method inside the class, so we make it private . If the width is zero then we just
return the original string. Otherwise, we assemble the string to be output in the StringBuffer object,
result . If the string, str , has more characters than the field width, then we fill result with X's.
Alternatively, you could mess up the nice neat columns here and output the whole string as-is instead.
If the length of str is less than the field width, we append the appropriate number of spaces to
result . We then insert str at the beginning of result (index position 0), or the end (index position
result.length()) . Finally, we return a String object that we create from result by calling its
toString() method.
We can now implement the print() methods and println() methods in our class very easily using
the pad() method. Here's how the print() method for type long looks:
// Output type long formatted in a given width
public void print(long value) {
super.print(pad(String.valueOf(value))); // Pad to width and output
}
The print(long value) method calls the static valueOf() method in the String class to convert
the value to a character string. The string is then passed to the pad() method to create a string of the
required length, and this is passed to the print() method belonging to the superclass, PrintWriter .
Search WWH ::




Custom Search