Java Reference
In-Depth Information
The print() method for a double value will be almost identical - well the body of the method
is identical:
// Output type double formatted in a given width
public void print(double value) {
super.print(pad(String.valueOf(value))); // Pad to width and output
}
The print() method for a String value is not a lot different:
// Output type String formatted in a given width
public void print(String str) {
super.print(pad(str)); // Pad to width and output
}
You should now be able to implement all the other versions of print() similarly to these so add
print() methods to the FormattedWriter class for types int , boolean , char , and float .
The println() methods that you also need to add are not very different. You just need to call the
println() method for the base class in each case. For instance, we can implement the println()
method for type int like this:
public void println(int value) {
super.println(pad(String.valueOf(value))); // Pad to width and output
}
Add the other println() methods for the remaining primitive types. You can block copy all the print()
methods and then modify the copies as a shortcut to save typing. Make sure you change the method
name and the print() call in the body in each case though.
If you want more flexibility with objects of the FormattedWriter class, you can add a setWidth()
member to change the field width and perhaps a getWidth() member to find out what it is currently.
The setWidth() method will be:
public void setWidth(int width) {
if(width >= 0)
this.width = width;
}
We test for a non-negative value before setting the width. Here we need to allow the possibility of
resetting the width to zero, whereas in the constructor we only want to set width for a non-zero positive
argument value. Now we can dynamically set the width for a FormattedWriter object, and all
subsequent output using the object will be in a field of the width that we specify.
It's ready to roll, so let's give it a whirl.
Search WWH ::




Custom Search