您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes
Introduction
Content
Apply
Reflect
Extend
previous.gif
 (3087 bytes)
next.gif
 (2959 bytes)
 
 
 
Content Index
Content Page # 4


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()
     }

 
image1.gif (1666 bytes) Exercise 1 ?if' test
Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright © 1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg