Game Development Reference
In-Depth Information
On the right-hand side of the equals sign, you have an
evaluated expression
, for
instance, “x is equal to 3,” followed by a
question mark
and then two numeric values
that are separated from each other, using the
colon
, and, finally, a
semicolon to ter-
minate
the conditional operator statement. If you wanted to set a variable
y
to a value
of
25
if
x
is equal to
3
, and to
10
if x is not equal to 3, you would write that conditional
operator programming statement by using the following Java programming logic:
y
=
(x
==
3)
?
25
:
10
;
Next, you are going to look at Java logic control structures that leverage the operat-
ors you just learned about.
JavaConditionalControl:DecisionMak-
ing or Loops
As you have just seen, many of the Java operators can have a fairly complex structure
and provide a lot of processing power, using very few characters of Java programming
logic. Java also has several more complicated
conditional control
structures, which
can automatically
make decisions
or
perform repetitive tasks
for you, once you have
set up the conditions for those decisions or task repetitions by coding the Java
logic
control
structure.
In this section, you will first explore decision-making control structures, such as the
Java
switch-case
structure and the
if-else
structure. Then, you will take a look at Java's
looping control structures, including
for
,
while
, and
do-while
.
Decision-Making Control Structures: Switch-Case and
If-Else
Some of the most powerful Java logic control structures allow you to define
decisions
that you want your program logic to make for you as the application is running. One
such structure offers a case-by-case, “flat” decision matrix; the other has a cascading (if
this, do this; if not, do this; if not, do this; and so on) type of structure that evaluates
things in the order in which you want them examined.
Let's start by looking at the Java
switch
statement, which uses the Java switch
keyword and an expression at the top of this decision tree and then uses the Java
case