Daily Archives: June 6, 2012

Java || Snippet – Custom Setw & Setfill Sample Code For Java

This page will consist of a brief implementation of setw/ios::width and setfill/ios::fill in Java.

If you are a C++ programmer, no doubt you have used the setw and setfill commands many times. It makes formatting output like this very clean and simple (see below).

Ending balance:................. $ 6433.47
Amount of deposits:............. $ 1750.00
Amount of withdrawals:.......... $ 420.00
Amount of interest earned:...... $ 103.47

But to my amazement, I could not find a very suitable replacement for the setw/setfill functions in Java. Using simple for loops, the methods provided on this page has the ability to mimic both functions which are available in C++.

Included in the sample code are the following:

== SETW ==

(1) right - Justifies string data of size "width," filling the width to the start of the string with whitespace

(2) left - Justifies string data of size "width," filling the width to the end of the string with whitespace

== SETFILL ==

(3) right - Justifies string data of size "width," filling the width to the start of the string with a filler character

(4) left - Justifies string data of size "width," filling the width to the end of the string with a filler character

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

Also, you must understand minimal object oriented programming to use this code!

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above snippet is similar to its C++ counterpart. Here is a sample program demonstrating its use.

Once compiled, you should get this as your output