Selection: IF匛LSE with
compound statements
Just as the statement to execute for
an if
statement be a compound statement,
so also can the statement following else
be a compound statement. In fact,
as a general rule in Java, wherever there is a single statement, braces
can be inserted and a compound statement can be introduced.
For example, we might wish to perform
more than one action if the temperature is too high, and more that one
action otherwise:
if
(temperature > 78)
{
soundAlarm();
displayFlashingLight( red );
triggerAlarmAtFireStation();
}
else
displayFlashingLight( green );
Or perhaps, perform multiple actions
in either case (so as well as the fire alarm device flashing a green light
if the temperature is not too hot, it also sends a message to test the
heating system in case the temperature is too cool):
if
(temperature > 78)
{
soundAlarm();
displayFlashingLight( red );
triggerAlarmAtFireStation();
}
else
{
displayFlashingLight( green );
testHeatingSystem()
}
Or perform a single action if the test
is true, and multiple actions if the test is false:
if
(temperature > 78)
soundAlarm();
else
{
displayFlashingLight( green );
testHeatingSystem()
}
Back
to top
RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex
University. All rights reserved.
webmaster@globalcampus.com.eg
|