Macromedia Flash MX 2004 ActionScript Programming Tutorial

Switch() and Case Statements

For extended if and else if statements, you can use the switch() and case statements instead. switch() returns a value from an expression, so isn’t limited to true or false evaluations:

var planetID = planet_menu.selectedItem;

switch (planetID) {

case 0:

planets_mc.gotoAndPlay(“Earth”);

case 1:

planets_mc.gotoAndPlay(“Mars”);

case 2:

planets_mc.gotoAndPlay(“Venus”);

case 3:

planets_mc.gotoAndPlay(“Jupiter”);

default:

planets_mc.openingmusic.start();

}

The default clause is used to execute any code instead of or in addition to the code executed by the case clauses. Depending on the switch() statement, one or more case clauses will execute—that is, the value in the switch() statement may or may not match more than one of the values given in the case clauses. In our case, the user will only select one item (from the menu), and the code assigns the value of the selected item in the menu to the variable planetID. This value is matched to one of the case clauses, which executes the code. After the remainder of the case clauses are checked for matching values, the code in the default clause is executed.

You don’t have to include a default clause, but it tells Flash what to do if the value doesn’t match any of the ones given in the case clauses. It also executes even if the value matches one or more of the case clauses.

To prevent execution of multiple case clauses, you can add the break action to force Flash to stop evaluating the expression after it executes the actions in the first matching case clause:

var planetID = Math.round(Math.random()*3);

switch (planetID) {

case 0:

planet = “Earth”;

break;

case 1:

planet = “Mars”;

break;

case 2:

planet = “Venus”;

break;

case 3:

planet = “Jupiter”;

break;

}

planets_mc.gotoAndPlay(planet);

The code above generates a random whole number between 0 and 3, matches the number to a case clause to assign a value to the planet variable, and then leaves the switch() statement to execute the action outside the switch() statement—playing the planets_mc movie clip at the frame containing the label that matches the contents of the planet variable.

Macromedia Flash MX 2004 ActionScript 2.0 Tutorial and Free Online Training Course

In this section, you learned about:

  • If Statements
  • Switch() and Case Statements

One Comment

  1. zoe

Leave a Reply

Your email address will not be published. Required fields are marked *