YOUR FEEDBACK
Architect0001@Nubifer.com wrote: Cloud Computing is a broad term. Simply searching "Cloud Computing" on Google wi...


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
MXDJ TOP LINKS YOU MUST CLICK ON !


Taking Action
Learning ActionScript version 2.0, part 2

In Part 1 I introduced you to very basic concepts of ActionScript 2.0. We looked at some simple programs such as setting a variable, basic object-oriented concepts, and some basic interaction with the Flash MX 2004 Interface.

It is important to understand one fundamental concept: for a computer program to be a computer program, it must have three basic capabilities:

  1. It must be able to perform a sequence of instructions.
  2. It must be able to have a decision structure.
  3. It must have a repeating structure.
The first one we certainly saw in Part 1 (Vol. 2, issue 12) of this series. Unless told to do otherwise, ActionScript 2 (as well as any program) will execute a line of code. Then, when it is finished executing that line of code, it will go on to the next one. Here, in Part 2, we will look at the second capability of making decisions. Before we begin, we must understand some programming basics.

Pseudocode
When I conduct my classes, the most common comment I get from beginning programmers is, "I have learned all of these great tools. Now, how do I use them for projects I work on?"

The key is in one word: Pseudocode!

All any computer does, even the most sophisticated, is carry out a predefined set of instructions. As sophisticated as they may seem, computers cannot vary from this set of instructions.

To understand pseudocode, let's try a little experiment. Let's pretend you don't have a computer; instead, you have to write the instructions out and tell someone how to do something by hand. As a very simple example, say you're teaching someone how to acknowledge a customer's payment of a bill. The pseudocode may go something like this: if the customer paid his bill in its entirety, send him a letter that says "your balance is 0." If the customer still has a balance, send him a letter telling him he still has a balance and write in what that balance is. Finally, if the customer overpays his bill, send him a letter showing that he has a credit and write in what that credit is.

Believe it or not, this is the first step to writing a computer program. We analyze the steps needed to accomplish the task and write those steps out informally. Finally, when we have all the steps laid out, we translate them into whatever computer code we are using (AS2, Java, Visual Basic, etc.). For really sophisticated and complex programs, you may even want to develop flowcharts (I will discuss flowcharts next month).

Now we can start to translate it to Flash ActionScript.

For starters, we'll need to build the user interface. We will need a field for the present balance, amount paid, message, and a button to trigger to action. The user interface should look something like Figure 1.

While this is not essential, notice that I set the dynamic text, static text, and UI components on separate layers. Also, I created an action layer to place some AS code. Additionally I made the balance due a dynamic text field and the amount paid as an input text field. They are called, respectively, balanceDue_txt and amountPaid_txt (in Part 1 of this series I discussed naming conventions). I called the button paid_btn and, for the output, I used a TextArea component called message_txt.

Normally you would get the balance due from an outside data source; that is outside of the scope of this article, so we'll write a line of code to set it for us.

Go to the actions layer, open the Actions Panel, and enter the following line of code:


balanceDue_txt.text = "235.00";

Remember, the text property sets the text for the balanceDue_txt object. If you test it, you should see something similar to Figure 2.

The rest of the code will be tied to the button, so click on the button component and go to the Actions Panel.

You need to build the code within an event. For most buttons, the event is press. Your opening shell code should look as follows:


on(press)
{

}

Now, here is a little quirk that is true of most programs today: TextFields are just that, text. All they can work with is text. However, we need to perform some calculations to determine a balance due or credit. Happily, Flash has a Class file all ready to help us out (Class files were discussed in Part 1). This file is called Number. We can convert the text in balanceDue_txt to a number by setting the following variable:


on(press)
{
	var due:Number  = Number(this._parent.balanceDue_txt.text);
}

As we discussed in Part 1, we set the variable "due" to be of data type Number. Next, we told AS2 to convert the text property of balanceDue_txt to a number. (Note: this._parent has to do with the relationship of the components to the time line. We will be discussing this up the road a bit. For the time being, when selecting components, use the Insert a Target Path tool located in the toolbar of the Actions Panel.)

We now need to do the same for the amountPaid_txt field.


on(press)
{
	var due:Number = Number(this._parent.balanceDue_txt.text);
	var paid:Number = Number(this._parent.amountPaid_txt.text);
}

Finally, we will to need to calculate the balance left after the payment is made. We can do this with a variable that will hold the calculation as follows:


on(press)
{
	var due:Number = Number(this._parent.balanceDue_txt.text);
	var paid:Number = Number(this._parent.amountPaid_txt.text);
	var newBalance:Number = due - paid;
}

Again, this variable is of data type Number. As we discussed in Part 1, strict data typing can prevent a lot of possible errors up the road.

We can give our little program a quick test by adding the following code:


on(press)
{
	var due:Number = Number(this._parent.balanceDue_txt.text);
	var paid:Number = Number(this._parent.amountPaid_txt.text);
	var newBalance:Number = due - paid;
	this._parent.message_txt.text = "The balance due is " + newBalance;
}

The + connects the literal text (enclosed in quotes) with a variable. This is called concatenation. Believe it or not, when you concatenate, everything is automatically converted back to text.

If you give the program a test, type in a payment amount and click the button; you should see something like Figure 3. Do not use a dollar sign when you type the number. We will not be concerned about formatting the numbers in this article. (Note: if you don't type a number or use the dollar sign, you might get a NaN in the TextField box. We will be fixing that shortly.)

It's now time to get to the subject at hand. If you set a number less than $235, you'll see the number. If you set a payment amount greater than $235, you end up with a negative number. If you pay exactly $235, it will show 0 as the balance. In all situations, the message is exactly the same with only the number changing.

We can give the message a bit more flexibility by using a decision structure. We have four possible scenarios:

  1. The user types an amount less than the balance.
  2. The user types an amount greater than the balance.
  3. The user types an amount equal to the balance.
  4. The user does not type any number.
We use an if/else structure. The generic syntax is:


if (condition to test for)
{
}

The condition to test for returns either true or false (in computer terms, we call this a Boolean expression). Let's begin by taking out the line of code that sets the message_txt.text property. You can do this by either deleting it or commenting it out with the // characters (a discussion of commenting occurred in Part 1).

Let's set the following if statement.


on(press)
{
	var due:Number = Number(this._parent.balanceDue_txt.text);
	var paid:Number = Number(this._parent.amountPaid_txt.text);
	var newBalance:Number = due - paid;
	if (newBalance > 0)
	{
	}

}

This code contained within the {} will run only if the conditional statement is true (in this case, if newBalance is greater than 0). We will tell it to set the message as follows:


if (newBalance > 0)
	{
		this._parent.message_txt.text = "You have a balance of " + newBalance;
	}

If you test the movie and type an amount less than the balance, say 200, the message box displays the message. However, if you type an amount that is greater, there is no change in the message. This is because an amount that is greater will return a condition that is false and the code within that if statement will not run.

We now need to handle the second possibility where the user types an amount greater than the balance. In Listing 1 we append to an "if" statement with "else if."

If you now test the movie and type an amount greater than the balance, say 300, a message will be displayed. You may notice that the amount displayed is a negative number. This is easily fixed by a tiny algebraic adjustment to the code.


this._parent.message_txt.text = "You have a credit of " + -newBalance

That negative sign before the variable negates the negative sign (back to high school algebra).

You should be starting to get the idea, but we will now see a couple of fine points. Let's address the third scenario where the user types an amount equal to the balance due. Of course, since we are appending another if statement, we will use an else if (see Listing 2).

Notice that in the conditional statement I used an = = as opposed to a single =. The double equal (= = ) is called a comparison statement because it is comparing what is on the left of the equal signs to what is on the right. A single equal sign is called an assignment statement because it assigns what is on the right side of the equal signs to what is on the left. Please note that there cannot be a space between the equal signs.

Finally, at the end of a decision structure you can place an else statement. The else is the code to execute if none of the if statements returns a value of true. Since it executes automatically if none of the if statements returns as true, it has no conditional statement of its own. In our simple example, we are going to inform the user that he did not type a number (see Listing 3).

Remember, the else statement is optional. If you don't use it, control of the code will return to the first line of code after the decision structure.

While each of our statements has only one line of code within it, it is not unusual to have many lines of code contained within the braces. As a matter of fact, in some cases there could be an additional if statement within an if statement. This is called an embedded statement. It might look something like this (this is not a working piece of code; it's just an example):


if (newBalance > 0)
	{
		this._parent.message_txt.text = "You have a balance of " + newBalance;
		if (newBalance > 50)
		{
			this._parent.message_txt.text = "...."
		}
	}

In one situation, I actually had five levels of if statement.

In our small example, we have no way of predicting what number the user will type. However, let's assume we have a program where the user is restricted to only certain selections. For example, let's say that the user can only type either 1, 2, or 3. Rather than build a series of if statements, you may find it a bit easier to use a variation of a decision structure called a Switch Statement. Our code might look something like Listing 4 (this is not meant to work in place of the above example).

There are a few things that need to be noted here. The beginning of the switch statement accepts the variable (in this case, the variable called selection) and assigns it to a matching case. Notice that at the end of each case there is a colon. When the code is completed for that case, the keyword break is used. This is the equivalent of a closing brace in an if statement. If you do not use the break keyword, the program will continue to the code for the remaining cases.

Finally, if something is entered that does not match any of the cases, it's a good idea to use a default case. This is a general catch-all.

Next month we will talk about looping structures.

About Charles E. Brown
Charles E. Brown is the former editor-in-chief of MX Developer's Journal. He is the author of Fireworks MX from Zero to Hero and Beginning Dreamweaver MX. He also contributed to The Macromedia Studio MX Bible. Charles is a senior trainer for FMC on the MX product family.

LATEST FLEX STORIES & POSTS
This is my final blog from the Adobe MAX 2008 conference.
I spoke on a panel at Mashup Camp this week on why Ajax Standards matter. I was quoted by Doug Henschen of Intelligent Enterprise as saying that we are locked in a struggle for the soul of the web, so I thought I would expand on that theme. Just because the web has been open so far doe...
New releases of Flex software were announced at MAX. How Flash Catalyst works.
Adobe and ARM are gonna put Flash Player 10 and AIR, the stuff of web video and rich Internet apps, on ARM widgets by the second half of next year. They mean phones, set-tops, MIDs, TVs, car mojo and personal media devices, which have so far only had access to Flash Lite, not the best ...
Notes from the openning day of Adobe MAX 2008
Of all domestic air carriers, I like Continental the most. They showed Mamma Mia and the food was bearable. Last month, I was in the air for 14 hours flying to Japan, and now the trip across the USA is a piece of cake. I have only carry luggage with me. This small bag has all the cloth...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

ADS BY GOOGLE