Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

forLoops 97

These statements are executed 1,000 times. The loop starts by setting the
dexvariable equal to 0. It then adds 1 to dexduring each pass through the
loop and stops looping when dexis no longer less than 1,000.


As you have seen with ifstatements, a forloop does not require brackets if
it contains only a single statement. This is shown in the following example:


for (int p = 0; p < 500; p++)
System.out.println(“I will not sell miracle cures”);


This loop displays the text “I will not sell miracle cures” 500 times.
Although brackets are not required around a single statement inside a
loop, you can use them to make the block easier to spot.


The first program you create during this hour displays the first 200 multi-
ples of 9: 9 ×1, 9 ×2, 9 ×3, and so on, up to 9 ×200. In NetBeans, create a
new empty Java file named Ninesand enter the text in Listing 8.1. When
you save the file, it is stored as Nines.java.


LISTING 8.1 The Full Text of Nines.java
1: classNines {
2: public staticvoidmain(String[] arguments) {
3: for (int dex = 1; dex <= 200; dex++) {
4: int multiple = 9 * dex;
5: System.out.print(multiple + “ “);
6: }
7: }
8: }


The Ninesprogram contains a forstatement in Line 3. This statement has
three parts:


. Initialization: int dex = 1, which creates an integer variable called
dexand gives it an initial value of 1.
. Conditional: dex <= 200, which must be true during each trip
through the loop. When it is not true, the loop ends.
. Change: dex++, which increments the dexvariable by one during
each trip through the loop.


Run the program by choosing Run, Run File in NetBeans. The program
produces the following output:


NOTE
An unusual term you might hear
in connection with loops is iter-
ation. An iteration is a single
trip through a loop. The counter
variable that is used to control
the loop is called an iterator.
Free download pdf