Switch Statement

Switch Statement

Flash CS4 ActionScript 3.0 Tutorial

 

How to Compare Values and Make Logical Boolean Decisions with Flash ActionScript

 

 

Conditional Statements are used to test equations to see if they are true or false. If the statement is true, one event happens. A false outcome would drive a different event.

There are multiple Conditional Statements in ActionScript. For more information, see topics, If Statement, If, Else Statement, If, Else If, Statement or If, Else If, Else Statement.

The Switch Statement is a simpler way to ask the same questions. In this example we will demonstrate using a Switch Statement.

Conditional Comparisons

Often times values are compared to determine if one is larger, they are equal, or not equal to each other. The following is a list of ActionScript comparisons. The And and Or symbols are used with more complex comparisons.

Equals (==)

Not Equal To (!=)

Greater Than (>)

Greater Than or Equal To (>=)

Less Than (<)

Less Than or Equal To (<=)

Or (||)

And (&&)

 

Step One

Open a new document and name the default layer, Actions.

Step Two

Option double-click (PC - Alt double click) the first keyframe of the Actions layer to open the ActionScript panel.

Step Three

Copy/Paste the following code in the ActionScript Panel:

var value01:uint=3;

switch (value01){

case 1:

trace("Only One Left");

break;

case 2:

trace("Only Two Left");

break;

case 3:

trace("Only Three Left");

break;

default:

trace("Game Over");

};

Step Four

Click the Auto Format icon in the Actions panel.

Step Five

Test your movie by pressing Cmd/Return (PC - Ctrl/Enter). Only Three Left appears in the Output panel.

Dissecting the Code

The first line establishes a new variable named value01 and sets its value to 3.

The switch statement asks if value01 is equal to 1, 2, or 3. If it equals any other value, the default statement says the game is over.

The 1, 2, or 3 could be substituted with any values. If the switch statement equals that value, then the trace statement is run. Once one of the conditions is met, the break statement tells ActionScript to move on to the next line of code after the switch statement.

In this example, value01 is set to 3 so the Output panel displays, Only Three Left.

Changing value01 variable to 2 would make the 2nd case true. A value of 1 makes the first case true. Any value besides 1, 2, or 3 tells the user that the game is over.

 

Royalty-Free Stock Video at Pond5