Game Development Reference
In-Depth Information
scenarios and greater. I use this switch-case structure extensively in my topics covering
Android.
Next, let's take a look at the other types of conditional control structures that are
used extensively in Java, the looping programming structures. These allow you to ex-
ecute a block of programming statements a predefined number of times (using the for
loop) or until an objective is achieved (using a while or a do-while loop).
LoopingControlStructures:While,Do-While,andFor
Whereas the decision tree type of control structure is traversed a fixed number of times
(once all the way through, unless a break [switch-case] or resolved expression [if-else]
is encountered), looping control structures keep executing over time, which, with re-
spect to the while and do-while structures, makes them a bit dangerous, as an infinite
loop can be generated, if you are not careful with your programming logic! The for
loop structure executes for a finite number of loops (the number is specified in the
definition of the for loop), as you will soon see in this section.
Let's start with the finite loop, covering the for loop first. A Java for loop uses the
following general format:
for (initialization; boolean expression; update equation) {
programming statement one;
programming statement two;
}
As you can see, the three parts of the evaluation area of the for loop are inside the
parentheses, separated by semicolons, as each contains a programming statement. The
first is a variable declaration and initialization, the second is a boolean expression eval-
uation, and the third is an update equation showing how to increment the loop during
each pass.
To move the InvinciBagel 40 pixels diagonally on the screen, along both X and
Y, the for loop is as follows:
for (int x=0; x < 40; x = x + 1) { // Note: an x = x +
1 statement could also be coded as x++
invinciBagelX++; // Note: invinciBagelX++ could be
coded invinciBagelX = invinciBagelX + 1;
invinciBagelY++; // Note: invinciBagelY++ could be
Search WWH ::




Custom Search