- Learning Java by Building Android Games
- John Horton
- 234字
- 2021-07-23 19:02:26
For loops
A for
loop has a slightly more complicated syntax than while
or do while
loop as they take three parts to initialize. Have a look at the code first then we will break it apart.
for(int i = 0; i < 10; i++){ // Something that needs to happen 10 times goes here }
The apparently obscure form of the for
loop is clearer when put like this:
for(declaration and initialization; condition; change after each pass through the loop).
To clarify further we have:
- Declaration and initialization: We create a new
int
variablei
and initialize it to zero. - Condition: Just like the other loops, it refers to the condition that must evaluate to true for the loop to continue.
- Change after each pass through the loop: In the example
i++
means that 1 is added/incremented toi
on each pass. We could also usei--
to reduce/decrementi
each pass.for(int i = 10; i > 0; i--){ // countdown } // blast off i = 0
Note
Note that break
can also be used in for
loops.
The for
loop essentially takes control of initialization, condition evaluation and the control variable on itself.
Nested loops
We can also nest loops within loops. For example, take a look at this next code.
int width = 20; int height = 10; for(int i = 0; i < width; i++){ for(int j = 0; j < height; j++){ // This code executes 200 times } }
The previous code will loop through every value of j
(0 through 9) for each and every value of i
(0 through 19).
The question is why would we do this? Nesting loops is useful when we want to perform a repetitive action that needs the changing values of two or more variables. For example, we could write code like the above to loop through a game board that is twenty spaces wide and ten spaces high.
Also note that loops of any type can be nested with any other loop. We will do this in most of the projects in this book.