Calculator Program
Here you will learn about:
 | radio buttons |
 | the assignment operator (=) |
 | basic math functions |
 | the Val() function |
 | conditional branching |
 | loops |
We will make a calculator that can do the basic functions of addition,
subtraction, multiplication and division. Instead of trying to make the
calculator that looks like a pocket calculator, which would be difficult, we
will set it up as below.

Make a new Windows Application project with the name
'calculator'. Save the project
immediately with File>Save All (not Ctrl-S, for that only saves the form file).
Give the name Calculator, the location
H:\VB if you are at EEB3 (otherwise use the default location), give the
solution name Calculator and leave the box checked for the automatic
creation of a folder with that name to hold your project.
ALWAYS set the location to
H:\VB if you are saving a project at school.
Add the eight controls to the form and set the name and
text properties as shown above. When making controls of the same type,
you may wish to save time by copying a control and then pasting
additional copies onto the form. Note that the control at the right is a
label not a textbox (you knew this from the name already?) - we don't
want to anyone typing in the answer! For the label, set the backcolor
to white and the autosize property to false otherwise the control may
keep changing width to accommodate answers of different lengths. Set the
font size to 16 for all the controls - the easy way to do this is to first
select all the controls simultaneously inside a selection rectangle made
with the pointer tool. Set the form's text property to 'Calculator'.
It's a good idea to build programs a step at a time, making sure each step is
working before proceeding to the next step. Let's make a first step by asking
the program to simply add the contents of the two textboxes without
paying any attention to the radio buttons.
Double-click the button and type the following code between the
btnEquals_Click wrapper lines: lblAnswer.Text = txtX.Text + txtY.Text It's very important to realize that in Visual Basic the '='
operator does not usually work like an equals sign, instead it is an 'assignment
operator' that works out what is on the right hand side and then stores the
answer in the variable or property named on the left hand side. So a line
such as
x = 3 + 6
would evaluate the right hand side to equal 9 then store that number into the
variable called x. In English, you could read the above line as
'Set x to equal the result of 3 + 6'
In our program, the line
lblAnswer.Text = txtX.Text + txtY.Text should add together the contents of the txtX textbox and the txtY textbox and
store the answer in the text of the label called lblAnswer. You should find that the program gives you a result, but not the one you
expect. You may get answers like 1+1=11 or 2+3=23! Clearly, computers can be
pretty stupid sometimes! Or maybe it is NOT being so stupid - is it stupid to
say "book" + "case" = "bookcase"? (Try using your
calculator to add these words together). So this is what the computer is doing -
joining the
numbers together as if they were text characters rather than numbers. Our
problem is that sometimes the + operator in Visual Basic can be used to add
numbers but sometimes it works like the '&' character and simply joins
blocks of text together. We must force the computer to treat the contents of the
textboxes as numbers, not as text - this can be done by copying the numbers into variables that have been declared to contain
numbers (not text)
Visual Basic usually forces you to declare (create) variables before you
use them (you can switch off this obligation by including the line Option
Explicit off as we did in the Greeting project but that makes your program
more error-prone and is not recommended). Let's do this properly then and
declare to variables x and y which will be set up so that they can only
contain numbers (that way VB will add them as numbers, not text). Some programming languages force the
programmer to declare ALL the variables, but Visual Basic does not. We need
to do it here just so that we can specify that the variables will hold
numbers, not text or dates or anything else. There are several types of
number formats in VB including integer and double. We don't want to
create variables that can only hold integers otherwise we won't be able to
add together non-integer numbers such as 1.3 and 4.84. So we'll take choose
the double format (it's called 'double because it holds numbers more
precisely than the 'single' type).
We can declare a variable x to be of type 'double' with this line ('Dim'
is short for 'dimension'):
Dim x as double
To declare both x and y we could declare on separate lines or we can
declare them together like this:
Dim x, y as double
If the variables are only going to be used in one subroutine, as is the
case in our program, then the Dim statement should be placed inside the
subroutine, just under the first wrapper line.
Before we add the two numbers, then, we need to copy what is in the text
boxes into our two new variables. Replace your btnEquals_Click code with the
code below and try running the program - it should add correctly now. x = txtx.Text
y = txty.Text
lblanswer.Text = x + y
To make sure you're not lost yet, here's a snapshot of the code window,
including the class and subroutine wrapper lines. To make that annoying long
line legible I have put an underscore character '_' in the middle of
the line - that makes the line 'wrap' into tow 'half-lines' but please
understand that as far as VB is concerned this is still a single line of
code, not two. You can use the underscore trick yourself when you want a
very long line of code to wrap for easy reading but make sure that you put
the underscore immediately after a space like I did otherwise it will
not work properly.

By the way, what happens if you try to add 'book' + 'case' now? Is the result what
you would expect?
If you are busy clicking the different radio buttons then you haven't
understood yet that our program is paying no attention to them since we
haven't referred to them in our code yet. The code above always does
addition no matter which radio button is selected.
As a next step, let's modify the code so that the program only does the
addition if the optAdd radio button is selected. We will use an IF statement to
check whether the radio button is selected. Note that radio buttons have a
checked
property which is true only when the radio button is selected.
Including code that tests whether a certain condition is true and runs
code depending on the result is called conditional branching and it
is an extremely important part of all programming languages.
Modify the code like this:
x = Val(txtx.Text)
y = Val(txty.Text)
If optadd.Checked = True Then
lblAnswer.Text = x + y
End If
Note how the end of the IF structure has been marked by the line End If, and
note how the contents of the IF structure have been indented by pressing
the Tab
key character at the beginning of the line - this makes the program more legible
since we can more easily the If/End If pairing.
Run the program, and you should find that the addition happens only when the
radio button for addition is selected - this is a slight improvement on what we
had before.
Do you agree that the sentence "If it is true that it is raining then
take your umbrella" could be shortened to "If it is raining then take
your umbrella"? In a similar way, the second line above can be shortened
to
If optadd.Checked Then
In Visual Basic, a line that says
If (such and such) = true then
can always be shortened by omitting the '=True'. We are always trying
to write code that is compact and efficient, though should not compress
code to the extent that it becomes hard to understand.
Now that we have figured out how to make addition happen only when we want
it, it should be easy to modify the code to handle subtraction, division and
multiplication and division. Modify the code like this (note that you can save a
lot of typing by using copy and paste):
x = Val(txtx.Text)
y = Val(txty.Text)
If optadd.Checked Then
lblAnswer.Text = x + y
End If
If optsubtract.Checked Then
lblAnswer.Text = x - y
End If
Lost? Here's another snapshot of the code window as it should look now:

Test the program for subtraction, and then add the necessary code for division
and multiplication. The calculator program is now fully functional, though the
code is not quite as efficient as it could be. Rather than spending time trying
to make the code more efficient, concentrate now on adding features to your
program, for EXTRA CREDIT. Note that if you share your ideas with your friends
you may be harming your own grade, for if lots of people are able to add these
features then I will have to assume that it was very easy! Suggestions:
 | add another radio button that gives the square of the number in the left
text box. Remember that the square of x can be written as x * x
or as x2. In computer programming, the latter notation
becomes x^2.
|
 | add another radio button that gives the square root of the number in the
left text box. In Visual Basic, the System.Math.Sqrt() function can be used to
give the square root. For example System.Math.Sqrt(9) will return 3 and
System.Math.Sqrt(x)
will return the square root of x.
|
 | Try using your calculator to divide a number by zero. This will 'crash'
your program and make it close with an error message because division by
zero is illegal. Add code to your program that checks for division by zero
and makes sure that the program does not attempt it, giving a messagebox
warning instead.
|
 | Can you think of other features that you can add? You will get credit for
originality, and may even get partial credit for good ideas even if you
cannot quite get the code to work without my help... |
|