jasonfactor wrote:
There are likely a million ways to do this, but how about writing a class that does it for you?
Let's assume that the functionality wasn't offered in the Java API. We have a couple of choices regarding how to "design" this class. I'm going to offer you some tips on how to make this class a bit more useful, and hopefully, we'll both come away with a better appreciation on how to create a more general design (and I realize that you were probably thinking more in terms of just pumping this out for a class assignment -- or for someone else to do so).
OK, the first thing that I would think if I saw this class in the API is why does it force me to use only 4 characters and why can't I pad with something besides a space? You could obviously add the two additional parameters to your constructor for the pad character and the pad length OR add a second constructor leaving the defaults as a space and 4.
BTW, I'm going to ignore the truncation rule that you introduced. This class will just do "padding' for the moment. If you want to truncate stuff, you should probably create a separate class. And we should probably rename the class to something more appropriate like FormatString.
Code:
public FormatString(String theString){
this.theString = theString;
}
public FormatString(String theString, char padCharacter, int length) {
this.theString = theString;
FORMAT_MASK = length;
PAD_CHARACTER = padCharacter;
}
Good -- the class is already more useful and all we've done so far is add a constructor. =)
The next thing to consider is the "how is someone going to use this class" sort of thought. I don't see people really wanting to instantiate an object every time they want to format a string. In all likelihood, they're going to use the object only one time and move on and need to format another string.
For example, I might have an array of integers. Do I really want to write something like...
Code:
for (int i = 0; i < arr.length; i++)
new FormatString(arr[i], pad, len).toString();
If the array contained a 1000 integers, I just allocated memory for the pad length 1000x, the pad char 1000x, etc. This is one of those cases where a static methods are probably more useful than a standard class method.
Code:
public class FormatString {
public formatString(String s, char padChar, int length) {
StringBuffer sb = new StringBuffer(s);
int padLength = length - s.length();
for (int i = 0; i < padLength; i++)
sb.insert(0, padChar);
return sb.toString();
}
}
Looks pretty good to me. What do you think?