In this tutorial you will learn about variables, procedures, and using blocks from the Math library.
For this program, you will implement a Math Helper that will either add or subtract two numbers entered by the user.
The components used for this interface are the following:
Hints:
Note, we will improve this version later by using Procedures to make our code cleaner.
result is a global variable that will store a numerical value. Think of it as a memory cell that stores information that can be accessed anywhere in your program. You can find the block to create the global variable in the Variables Blocks. Drag it over and replace name with result. You can find the block to represent the value 0 in the Math Blocks.
when add.Click is a block of instructions that will execute when the Add button is clicked.
when subtract.Click is exactly the same as when add.Click, but will subtract rather than add the numbers.
Once your program looks like the program above, test it out to make sure all functionality works as expected.
You will notice that the second, third, and fourth instructions in both add.Click and subtract.Click are almost identical. Good program design will use as little repetition as possible, so next we will use procedures to make this code easier to read and less error prone.
The blocks below show how this program may be implemented by using a procedure to display the result of the calculation and clear the TextBoxes.
Using a Procedure Block, create a procedure and change the name procedure to a name describing what this procedure does (in our case displayResultAndClearTextBoxes.)
This procedure will have three steps: set the result Label, clear the num1 TextBox, and clear the num2 TextBox. Unfortunately, we want the result Label to display a "+" if the user clicked Add and a "-" if the user clicked Subtract. In order to allow this, we'll need to add an input to our procedure. To do this, use the blue icon on the upper left of the procedure block. Change the name of the input from X to something descriptive like operation.
You can easily drag the blocks to set result, num1, and num2 into the new procedure block. The only change you will need to make is to replace the "+" text block with a get variable block and select the variable operation.
Finally, in you will need to call the procedure in two places in your program. The call block is found in Procedures. Recall that the procedure requires an input, so from the call block you will need to provide a text block containing the operation: a + or -.
You are ready to test your program!
How would you, now, add the ability to multiply or divide the numbers?