Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

Enterprise Open Source Magazine Latest Stories . . .
With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
C12G Labs has just announced an update release of OpenNebulaPro, the enterprise edition of the OpenNebula Toolkit. OpenNebula 3.2, released two weeks ago, brings important benefits to cloud providers with a new easily-customizable self-service portal for cloud consumers, and builders w...
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