|
Note that once we have finished this Greeting program we will add the next
program, a calculator program, to the SAME FORM.
Calculator Program
Here you will learn about:
 | option buttons |
 | the assignment operator (=) |
 | basic math functions |
 | conditional branching |
 | loops |
We will make a calculator that can do the basic functions of addition,
subtraction, multiplication and division. It won't look much like the calculator
you've got in your bag - it will look like this:

Begin a new project and save it right away with the name
'Calculator'. Add these eight controls to the form and set the name and
caption/text properties as shown above. When making controls of the same type,
it may occur to you that you can do this by copying a control and then pasting
additional copies onto the form - this is OK as long as you choose NOT to create
a 'control array' when asked - we will learn about control arrays later. 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!
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 option buttons.
Double-click the command button and type the following code:
Private Sub cmdEquals_Click()
lblAnswer.Caption = txtx.Text + txtY.Text
End Sub 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.Caption = txtx.Text + txtY.Text should add together the contents of the txtX textbox and the txtY textbox and
store the answer in the caption 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 moving the numbers into variables that have been declared to contain
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, single 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 (more precise than single).
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
Note that variable declarations are normally placed outside any
subroutine, unlike all other code you have met. So copy and paste the above
like into your program, putting it above all the existing code.
Before we add the two numbers, then, we need to copy what is in the text
boxes into our two new variables. Replace your cmdEquals_Click procedure
with this one and try running the program - it should add correctly now.
Private Sub cmdgreet_Click()
x = txtx.Text
y = txty.Text
lblanswer.Caption = x + y
End Sub
Method 2
Now let's try using the Val() function to solve the problem. This
forces the computer to convert the 'numbers in the form of text' into real
numbers, so we no longer need to use the variable declaration method. Please
erase then, the variable declaration line that you added earlier Then modify the code so that it looks like this (I will use bold type to emphasize
changes):
Private Sub cmdEquals_Click()
x = Val(txtx.Text)
y = Val(txty.Text)
lblAnswer.Caption = x + y
End Sub
and try running the program again. Now you should find that 1+1=2, as
expected! What happens if you try to add 'book' + 'case' now? Is the result what
you would expect?
As a next step, let's modify the code so that the program only does the
addition if the optadd option button is selected. We will use an IF statement to
check whether the option button is selected. Note that option buttons have a value
property which is true only when the option button is selected.
Including code that test 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:
Private Sub cmdEquals_Click()
x = Val(txtx.Text)
y = Val(txty.Text)
If optadd.Value = True Then
lblAnswer.Caption = x + y
End If
End Sub
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 putting a Tab
character at the beginning of the line - this makes the program more legible.
Run the program, and you should find that the addition happens only when the
option button for addition is selected.
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.Value Then
In Visual Basic, a line that says
If ??????????? = 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):
Private Sub cmdEquals_Click()
x = Val(txtx.Text)
y = Val(txty.Text)
If optadd.Value Then
lblAnswer.Caption = x + y
End If
If optsubtract.Value Then
lblAnswer.Caption = x - y
End If
End Sub
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.
If you follow this
link you might be able to see the
calculator program running right in your browser (more probably your security
settings will stop your browser from showing it.) Using Visual Basic 5 to make programs ('applets') that can actually run
inside a web page is difficult or impossible but if you have VB6 at
home and if you follow the link on the same page then you will realize that it can be done.
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 option 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 option button that gives the square root of the number in the
left text box. In Visual Basic, the sqr() function can be used to
give the square root. For example sqr(9) will return 3 and sqr(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... |
|