Java Reference
In-Depth Information
Using Unary Operators in for Loops
To create a simple for loop that is to be repeated 10 times, the following for
statement can be used:
for (int i = 1; i<11; i++)
Many programmers use the identifier, i, instead of spelling out the word incre-
ment when creating a for loop. The first parameter declares and sets the i vari-
able to 1. The second parameter tests i to make sure it is less than 11. The third
parameter increments the variable by one, using the increment operator, ++.
When a for loop uses a decrement operator in the third parameter, it gives
the feeling of counting backward. For example, the following code:
for (int counter = 10; counter>0; counter--)
creates a for loop that executes 10 times.
When using a decrement operator, the counter in the second parameter
must be less than the value in the first parameter. If it is not, as in the following
code:
for (int counter = 1; counter<10; counter--)
the for loop will execute an infinite number of times, because the condition
always will be true. If the values in the first and second parameters are the same,
as in the following code:
for (int counter = 1; counter<1; counter--)
the program will compile, but the for loop never will execute.
Figure 5-13 displays the code to assign each element of the occupied array a
value of false, using a for loop in the Rooms() constructor method. The for loop
beginning in line 23 has only one dependent line of code in line 24 and thus
does not include braces. A for loop that has more than one line of code must
include braces around that code; if it does not, only the first line of code will
repeat. The other lines will execute once after the loop is completed.
When the Rooms object is instantiated in the driver class, lines 26 and 27
assign the passed values to the class level variables for use in all methods of the
Rooms class.
23
for ( int i=0; i< ( sm+non ) ; i++ )
24
occupied [ i ] = false ; //set each occupied room to false or empty
25
//initialize the number of smoking and nonsmoking rooms
26
numSmoking = sm;
27
numNonSmoking = non;
28
}
29
FIGURE 5-13
Search WWH ::




Custom Search