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

Print Friendly, PDF & Email

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) setwL - Right justifies string data of size "width," filling the width to the left of the string with whitespace.

(2) setwR - Left justifies string data of size "width," filling the width to the right of the string with whitespace.

== SETW/SETFILL ==

(3) setwLF - Right justifies string data of size "width," filling the width to the left of the string with a custom filler character.

(4) setwRF - Left justifies string data of size "width," filling the width to the right of the string with a custom 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

Leave a Reply