Professional Documents
Culture Documents
the
true
test
is
true
execute
the
statements
a2er
the
if-‐statement
Can
you
spot
the
problem
in
this
code?
Scanner console = new Scanner(System.in);
System.out.print(”How many magazines did you sell? ");
int percent = console.nextInt();
if (totalSales >= 50) {
System.out.println(”Congratualtions, you win an iPad");
}
if (totalSales >= 35) {
System.out.println("Congratualtions, you win an iPod");
}
if (totalSales >= 25) {
System.out.println("Congratualtions, you win a stylus");
}
if (totalSales >= 15) {
System.out.println("Congratualtions, you win a gift card");
} else {
System.out.println(”Keep up the good work!");
}
...
suppose you
sold 72
A
closer
no
>=50?
magazines
flow
no
>=35?
yes
making yes
more
no
50
>
sold
explicit
>=35?
yes
statement(s); true
if
test
is
} true
System.out.println("Zero"); true
if
test
is
} true
if
test
true
if
test
true
Example:
if (grade == ‘A’) {
}
Review
if
statements
• Devise
scenarios
for
different
types
of
if
statements
• Consider
– How
many
different
outcomes?
– Should
there
be
a
path
where
no
statement
is
executed?
– Can
you
use
well
designed
tests
to
combine
condiNons
and
eliminate
if
branches?
– Can
you
reduce
redundancy?
Returning
to
our
game
problem
• Three
condiNons:
every
player
falls
into
one
of
these
condiNons
NE
– NW,
purple
True
or
False
SW?
– SE,
red
False
True
SE?
– SW,
NE,
green
• if/else
if/else
• try
wriNng
this
code
Assume
a
player’s
posiNon
is
given
as
x,y
coordiantes
p1.x
and
p1.y
Note
that
posiNve
x
*
posiNve
y
=
posiNve
result,
NE,
green
negaNve
x
*
negaNve
y
=
posiNve
result,
SW,
green
posiNve
x
*
negaNve
y
=
negaNve
result,
SE,
red
negaNve
x
*
posiNve
y
=
negaNve
result,
NW,
purple
posiNve
x
*
posiNve
y
=
posiNve
result,
NE,
green
negaNve
x
*
negaNve
y
=
posiNve
result,
SW,
green
posiNve
x
*
negaNve
y
=
negaNve
result,
SE,
red
negaNve
x
*
posiNve
y
=
negaNve
result,
NW,
purple
if (position >= 0) {
p1.color = green;
} else if (p1.x > 0) { Only players with
negative location
p1.color = red;
will test the p1.x
} else { therefore the only
p1.color = purple; two cases left are
} red or purple