In this tutorial you will create a simple calculator that allows a user to input two numbers and add them together.
Open Flash and create a new movie.
Select the Text Tool and draw a 2 text boxes on the stage. Open the Properties Inspector and change the Text Type to ‘Input Text’ for both the Input Text boxes. Change the Instance Names to 'firstNum' and 'secondNum'. You should also select the option to 'Show border around text' so that the text boxes shows up against the background.
Add a button to the stage which will be used to add the two numbers together.
Now add a Dynamic Text box to the stage. This will display the result of adding the two numbers together. Change the Instance Name of this box to 'resultNum'. Select the option to 'Show border around text' so that the text box shows up against the background. Your application should now look something like that shown in the diagram below.
Attach the following Actionscript to the button instance:
on (release){
resultNum.text=firstNum.text + secondNum.text
}
Test your application, and you should find that there is a problem - it doesn't quite work as expected. The numbers aren't added together, they are concatenated i.e joined together end-to-end.
This is because Flash is adding two 'string' variables together. It is treating the numbers as text characters, rather than numbers. To overcome this you need to use an in-built Flash function to convert the text to numbers.
To fix the problem, replace the current button code with that shown below:
on (release){
resultNum.text=number(firstNum.text) + number(secondNum.text)
}
The 'number' function converts the string characters into numbers, which allows tham to be added together rather than concatenated.
Try out the finished application below:
Additional things to try
Add the capability to subtract, multiply and divide.
For clever clogs: Display a useful error message if a user types in non-numeric data i.e. letters or invalid symbols.