Be careful to avoid infinite loops. For both while and do-while
loops, make sure that the Boolean expression eventually becomes false.
Be sure that you are not confusing “less than” with “less than or equal”; or “greater than” with “greater than or equal”, when you are coding the Boolean condition for
loops.
Use formatting to indicate subordination of control structures. The statements that belong inside a control structure should be indented by a tab or about 3 spaces. Good formatting is especially needed with nested control structures to make the code easier to read. For example:
for (int row = 1; row <= 5; row++){
// if row is odd, print a row of '*', otherwise print a row of '-'
if (row % 2 == 1){
c1 = '*';
}else{
c1 = '-';
}
for (int col = 1; col <= 10; col++){
System.out.print(c1);
}
System.out.println();
}
Here are some basic guidelines for selecting the appropriate looping tool in Java:
for
loop - used when the number of iterations can be determined before entering the loop.
while
loop - used when the loop could potentially occur zero times.
do-while
loop - used when the loop body should be executed at least once.
A valuable strategy for developing the Boolean expression for a conditional loop is the idea of negation. This technique consists of two important steps:
1. What will be true when the loop is done? This will be stated as a Boolean expression.
2. Then write the opposite of this Boolean expression.
For example, suppose we wanted to read positive integers from the keyboard until the running total is greater than 50.
What will be true when the loop is done? total > 50
Negate this expression: total <= 50.
We use the negated expression as the boundary condition of our loop.
total = 0;
do
{
System.out.println("Enter an integer ---> ");
num = keyboard.readInt();
total += num;
}while (total <= 50);
The expression (total <= 50)
can be thought of as “keep doing the loop as long as total is less than or equal to 50.”