07
up till now, all the code we've written was always executed.
at first thought, this may sound perfectly desirable, but it can be limiting.
we're forced to follow the same course of action each time through the program.
if we could specify blocks of code that wouldn't always execute, that would allow us alternatives.
we could do some things only when we felt like it—when the conditions were right.
if, then; else
so first we need to be able to specify conditions, statements that evaluate to be
true, or false. remember these are boolean expressions,
and we use them already in our loops to check if we should continue looping:
while (x >= 5) for (var y=0; y < x; y++)
var expensive:Boolean = false; var outrageous:Boolean = true; var y:Boolean = (5 < 28); var n:Boolean = (1+1 == 3); var stillPlaying:Boolean = inBounds();
&&, and logical OR– ||(price == cheap) && (style == outrageous) (color == green) || (color == brown)
conditional statements are composed using the keyword if, a boolean expression in
parentheses, and code to execute when the conditional expression evaluates to true
inside curly braces { }
if (outrageous && !expensive) { buy(); }or, to pick over the not-so-tasty strawberries:
if (green || brown) { discard(); }remember that the code inside the curly braces will be executed only in the event that the boolean expression is
true; at any other time execution of the program will skip right past,
ignoring what's inside the conditional statement.
else.
this allows us to act on the alternative, when the if expression is false
if (outrageous && !expensive) { buy(); } else { goToNewStore(); }now some code will be executed every time this program is run, but which code it is depends on the values of the two boolean variables
outrageous and expensive.
if..else clauses:
var choice:Number = Math.floor(Math.random() * 3); if (choice == 0) { // first option } else if (choice == 1) { // second option } else if (choice == 2) { // third option }or we could also use a switch statement:
var choice:Number = Math.floor(Math.random() * 3); switch (choice) { case (0) : // first option break; case (1) : // second option break; case (2) : // third option break; }both accomplish the same thing. some prefer the formatting of the
switch statement,
others prefer the familiarity of the if..else. they both execute very similarly.