Java Reference
In-Depth Information
This loop structure is sometimes called a Ñloop and a halfÒ.
Finally, if you know whether you need to go on after you have gone through the
loop once, then you use a
do/while
loop:
do
{
Do work
}
while
(condition)
However, these loops are very rare in practice.
Step 4 Implement the loop by putting the operations from Step 1 into the loop
body.
When you write a
for
loop, you usually use the loop index inside the loop body.
For example, Ȓget the next characterȓ is implemented as the statement
char ch = str.charAt(i);
Step 5 Double-check your variable initializations.
If you use a Boolean variable
done
, make sure it is initialized to
false
. If you
accumulate a result in a
sum
or
count
variable, make sure that you set it to 0
before entering the loop for the first time.
251
252
Step 6 Check for off-by-one errors.
Consider the simplest possible scenarios:
ȗ
If you read input, what happens if there is no input at all? Exactly one input?
ȗ
If you look through the characters of a string, what happens if the string is
empty? If it has one character in it?
ȗ
If you accumulate values until some target has been reached, what happens
if the target is 0? A negative value?
Manually walk through every instruction in the loop, including all initializations.
Carefully check all conditions, paying attention to the difference between