Java Reference
In-Depth Information
"The investment reached the target after
"
+ years + " years.");
Should years start at 0 or at 1? Should you test for balance < 2 *
initialBalance or for balance <= 2 * initialBalance ? It is easy
to be off by one in these expressions.
Some people try to solve off-by-one errors by randomly inserting +1 or Ċ1 until
the program seems to work. That is, of course, a terrible strategy. It can take a long
time to compile and test all the various possibilities. Expending a small amount of
mental effort is a real time saver.
Fortunately, off-by-one errors are easy to avoid, simply by thinking through a
couple of test cases and using the information from the test cases to come up with
a rationale for the correct loop condition.
An off-by-one error is a common error when programming loops. Think
through simple test cases to avoid this type of error.
Should years start at 0 or at 1? Look at a scenario with simple values: an initial
balance of $100 and an interest rate of 50%. After year 1, the balance is $150, and
after year 2 it is $225, or over $200. So the investment doubled after 2 years. The
loop executed two times, incrementing years each time. Hence years must start
at 0, not at 1.
In other words, the balance variable denotes the balance after the end of the
year. At the outset, the balance variable contains the balance after year 0 and
not after year 1.
233
234
Next, should you use a < or <= comparison in the test? That is harder to figure out,
because it is rare for the balance to be exactly twice the initial balance. Of course,
there is one case when this happens, namely when the interest is 100%. The loop
executes once. Now years is 1, and balance is exactly equal to 2 *
initialBalance . Has the investment doubled after one year? It has. Therefore,
the loop should not execute again. If the test condition is balance < 2 *
initialBalance , the loop stops, as it should. If the test condition had been
Search WWH ::




Custom Search