1 - use a loop to fill a string with a full row of the input name. 2 - use a loop to write all the full rows out 3 - write the last partial row, if needed.
Katrina recommended ... "How about a single loop which counts to 100, printing the name each time? You can use your namesPerRow variable to decide whether or not you need to put in a linebreak."
Which I am interpreting as suggesting I use an if-then check inside a single "count-to-100" loop. Would folks agree I'm interpreting this nitpick correctly? If so, I can certainly do that, but I'm lost as to the reason such an approach would be better. Any thoughts??
Thanks very much!
PS - Is this the sort of thing I should have just asked Katrina about in an email reply?
The point is to make code as readable as possible. The bigger your code is, the more there is to read. The art of writing simple, readable code is to write the least amount without sacrificing a clear message. By removing extra loops, you will make your code simpler and more readable, and as an added bonus, your code will be smaller.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Joined: Jun 17, 2008
I realize at this scale, any difference in performance will be negligible, but in principle, isn't there a performance issue?
For example, say I enter "Julie" as the arg. In my approach I check for ... - loop completion 13 times to fill a full row. - loop completion 7 times to output seven full rows. - need for a final partial row - loop completion 8 times to fill out the partial row.
Giving a total of 29 loop checks and 8 invocations of System.out.println
On the other hand the nitpick would lead to 100 loop checks plus 100 if-then checks, plus greater than 100 System.out.print and println executions.
Not trying to be a trouble maker. Just checking. Again, I realize at this scale, any real difference will be negligible, but the readability issue seems at least as marginal in this case.
In the meantime, I'll go ahead and make the suggested change.
Thanks very much.
Joined: Nov 03, 2006
In your version with three loops, you are concatenating Strings a LOT. For each String concatenation, you are creating (correct me if I'm wrong!) four extra objects.
So you would probably have to run profiling tests on each of the versions before deciding which performs better.
Also, there is the thing about premature optimization: you want to have the most readable code first, then later, if you determine that there is a performance problem, that is when you would consider how to optimize. Often, if you try to optimize too early, you miss some significant opportunities for improvement.
Joined: Jun 17, 2008
OK - thanks for that. I keep forgetting about strings being objects.
Also, your point about optimizing too early is well taken. I'll try to keep that in mind.