|
-
Jan 1st, 2011, 02:30 PM
#1
Thread Starter
Addicted Member
[VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator
This simple tutorial was just made to help some friends with a problem they were having in understanding basic principles of vb coding. Due to a lack of explanation, this basic calculator (presented in Ch.3 of their beginner book) was really giving them trouble. So I created one from scratch for them, that is a little bit more complicated, but only to show off many of the basics of coding in VB.
Keep in mind, this is a "Real Beginner's Guide", so any critiquing should only relate to such.
First, start a simple Vb project
On your main form (i renamed mine frmMain) place the follwing: (all can be drag and dropped from toolbox)
- Textbox named txtInput
- Label named lblResult
- RichTextbox named rtxShowWork
- 1 Button named btnClear
- 4 Buttons for Add, Subtract, Multiply, and Divide (name each as such with "btn" at beginning of the name)
After you have some fun playing with the controls and setting them to look like however you want, right click 'frmMain' in the Solution Explorer
Then select 'View Code' (NOT .designer code!)
Select all automatically created text (press Ctrl+A) and then press your 'Del' key to delete it all
Finally, start coding by following the code below, you don't need to include the comments, of course, which is every line that begins with a single quote.
However, in order for the program to work without errors, you will need every single line of actual code.
If you are a real beginner, please don't skip a step and get to know some of the easiest uses of Basic coding.
EZ Calc Code Code:
''' <summary>
''' EZ Calc Tutorial
''' JD McKinstry
''' First, it should be noted, as you become a
''' more experienced coder, you will find this tutorial
''' to contain very simple, non-standard practices. The
''' purpose of this is not to teach you to be company ready,
''' it is simply to teach some very basic examples of the
''' Basic Coding Language. Should you find this tutorial
''' beneath your skillset, then I advise you check out MicroSoft's
''' Developer Studio online and look up the Intermidiate Tutorials.
''' </summary>
Public Class frmMain
' This is simply the establishment of a Region
' Regions are useful in dividing up sections of code into similar catagories
' This is not extremely important for now, but helps to break down the compacted view,
' making it easier to see all the items in your code.
#Region " Vars/Properties "
''' <summary>
''' First things first, to do simple XML Comments like this one,
''' Simply place cursor 1 line above the method, property, or variable
''' you wish to document/comment on. Then simply type 3 single quotes;
''' such as the ones you see at the beggining of each line here.
''' In Visual Studio, this will automatically create a simple XML
''' Document/Comment layout!
''' This is useful later, when looking at your Object Library, as each
''' section in these comments is shown in an easy to read manner.
''' </summary>
''' <remarks>Notice, it doesn't add all featues, such as the 'example' feature seen below!</remarks>
''' <example>ezXML_Documentation = "This is a String"</example>
Private ezXML_Documentation As String
''' <summary>
''' Establish Enumerable for the 4 basic calculations.
''' This will later be used to determine which function
''' to use as your program "calculates"
''' </summary>
Enum calc
Add
Subtract
Multiply
Divide
End Enum
''' <summary>
''' This is a pre-.Net 4.0 standard for establishing a
''' "root variable" for later established properties.
''' This gives the Properties a variable to use for
''' interaction.
''' </summary>
Private _result As Double
Private _calcValue As calc
''' <summary>
''' These are both public properties which will be
''' used when 'doing the work' behind this calc program.
''' This first property is simply used to maintain the value
''' of our final result for each calcullation.
''' </summary>
Public Property result() As Double
Get
Return _result
End Get
Set(ByVal value As Double)
_result = value
End Set
End Property
''' <summary>
''' This second property will be used to store the present
''' value for the function being preformed. Remember our enum?
''' As you notice this property is an establishment of that enum,
''' meaning it can hold one value selected from that enum.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property calcValue() As calc
Get
Return _calcValue
End Get
Set(ByVal value As calc)
_calcValue = value
End Set
End Property
#End Region
Last edited by spyk3; Jan 1st, 2011 at 02:54 PM.
-
Jan 1st, 2011, 02:32 PM
#2
Thread Starter
Addicted Member
Re: [VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator
EZ Calc Code Code:
#Region " Events "
''' <summary>
''' This will be the first event you will deal with for most simple programs.
''' In Object Orientated Programing, events are used to help seperate the
''' 'do work' value of the code behind from the code used to establish a visual.
''' This event is triggered when the form is loaded and here, we simply want to
''' give the input textbox focus. This means, that whens the program loads,
''' the cursor will already be placed in the textbox and the user can immidiately
''' start typing in calculations.
''' </summary>
''' <param name="sender">This first parameter simply represents a 'sending' control.
''' This simply means that the value of 'sender' will be the control that
''' 'triggered the event'. This is usually the first parameter of form controller
''' events, however, your first parameter may be anything the person who wrote
''' the control or object establishes it to be. In other words, this is not always
''' your first parameter.</param>
''' <param name="e">In this case, this param is used to grab the 'message' passed
''' as this event fires. For more information, please see a more advanced tutorial,
''' as the explination of this variable is simple beyond the scope of this simple tutorial.</param>
''' <remarks></remarks>
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
txtInput.Focus()
End Sub
''' <summary>
''' These 4 button events trigger whenever a 'math' button is clicked.
''' As you will notice, I have very little code here, as it is simply better
''' to come up with a 'universal' method for multiple controls doing 'similar'
''' work. Of course, not all variables, or even the math is the same, but as
''' you will later see in the method, we conquer this issue with universal variables.
''' </summary>
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
doWork(calc.Add)
End Sub
Private Sub btnDivide_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDivide.Click
doWork(calc.Divide)
End Sub
Private Sub btnMultiply_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMultiply.Click
doWork(calc.Multiply)
End Sub
Private Sub btnSubtract_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubtract.Click
doWork(calc.Subtract)
End Sub
''' <summary>
''' This event simply resets our form to ground zero. As you learn more,
''' you'll note, there are multple ways to do this, but for now, I will
''' simply show you the 'straight forward' approach. This means simply
''' reseting each control on the form to its original value.
''' As you will also notice, I don't 'reset' all controls. Simply put,
''' not all controls contain a 'changing' value, and thus do not require a reset.
''' </summary>
Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
' First we reset our 2 properties
result = 0.0
calcValue = Nothing
' Next we reset all 'changing visuals' on our form
' In our case, this means 1 label, 1 textbox, and 1 richtextbox
lblResult.Text = "[Result]"
txtInput.Text = ""
rtxShowWork.Text = ""
' Finally, reset the focus of the form to the input textbox
txtInput.Focus()
' Tada! We are ready for our next set of calculations!
End Sub
''' <summary>
''' Here will deal with 2 issues.
''' First, if the user has pressed a calculation key, we dont want to display it
''' in the textbox, but we do want it to do the work. This event fires before
''' any text is actually sent to the textbox, thus, here is a good place to catch
''' errors key presses (such as typing in the letter 'U').
''' Second, if the user types anything else that is not a calculation or number
''' then we want to disreguard the key as it is usless to our current project.
''' </summary>
Private Sub txtInput_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInput.KeyPress
' Often times, Long IfElse Statements can be replaced with better practices
' but here, I simply want to break down the work taking place
' The first 4 parts of this if statement do 2 things
' 1st, if key pressed is a math symbol, then set the
' e.Handled property to "true" so that it will not
' be displyed in the text box
' 2nd, do the math associated with the key pressed
' The last part of this statement simply stops anything that is not a
' number from continueing onto the textbox
If e.KeyChar.ToString = "+" Then
e.Handled = True
doWork(calc.Add)
ElseIf e.KeyChar.ToString = "-" Then
e.Handled = True
doWork(calc.Subtract)
ElseIf e.KeyChar.ToString = "*" Then
e.Handled = True
doWork(calc.Multiply)
ElseIf e.KeyChar.ToString = "/" Then
e.Handled = True
doWork(calc.Divide)
ElseIf Not IsNumeric(e.KeyChar) Then
e.Handled = True
End If
End Sub
#End Region
-
Jan 1st, 2011, 02:33 PM
#3
Thread Starter
Addicted Member
Re: [VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator
EZ Calc Code Code:
#Region " Methods "
''' <summary>
''' Here i've established 4 very simple functions for preforming our
''' 4 basic math calculations. A function is good for this, as we can
''' pass in 2 variables and recieve an answer in return!
''' </summary>
Private Function mAdd(ByVal frstValu As Object, ByVal scndValue As Object)
' These first 2 variables ensre that our values passed in are in correct format for calculating
Dim tmpFrstValue As Double = CDbl(frstValu)
Dim tmpScndValue As Double = CDbl(scndValue)
' This 3rd variable is our math!
' Something to note about vb, when placed between 2 numeric values,
' a math symbol (such as the 4 in this program) is translated
' literally.
Dim tmpResult As Double = tmpFrstValue + tmpScndValue
' This is a real difference between a Function and a Sub Routine.
' Functions should always 'return' a value to the place where it's called.
' However, a sub will only return ZERO values, as it simply 'does work'
Return tmpResult
End Function
Private Function mSubtract(ByVal frstValu As Object, ByVal scndValue As Object)
Dim tmpFrstValue As Double = CDbl(frstValu)
Dim tmpScndValue As Double = CDbl(scndValue)
Dim tmpResult As Double = tmpFrstValue - tmpScndValue
Return tmpResult
End Function
Private Function mMultiply(ByVal frstValu As Object, ByVal scndValue As Object)
Dim tmpFrstValue As Double = CDbl(frstValu)
Dim tmpScndValue As Double = CDbl(scndValue)
Dim tmpResult As Double = tmpFrstValue * tmpScndValue
Return tmpResult
End Function
Private Function mDivide(ByVal frstValu As Object, ByVal scndValue As Object)
Dim tmpFrstValue As Double = CDbl(frstValu)
Dim tmpScndValue As Double = CDbl(scndValue)
Dim tmpResult As Double = tmpFrstValue / tmpScndValue
Return tmpResult
End Function
''' <summary>
''' This is our main Sub Routine. Here is where most of the 'work' happens
''' after a calculation button is pressed. This is established to keep from
''' having 'repetative' throughout each math button click.
''' </summary>
''' <param name="value">This is a prime example of a coder defined parameter.
''' Keep in mind, when writing your own methods, you can establish as many
''' parameters as you feel you will need.
''' This parameter provides a simple way to help deteremine
''' what math to perform, as that is the key difference between the
''' objects using this method.</param>
Sub doWork(ByVal value As calc)
' First, we set our universal 'what math' parameter,
' so that is any other method should need to know
' its value, we don't have to pass it as another parameter
calcValue = value
' Next, before calculating anything, we need to make sure the
' user ment to calculate somthing. This is accounting for user
' error. This simple practice helps in every prgrom to prevent
' such errors as trying to add 2 objects that are empty.
If Not txtInput.Text = "" Then
' With the opening work out of the way, we start on the meat
' 1st, for our case, we'll display the math about to take place
' in our RichTextBox
' The text being shown is as follows
' result = the current value of our result property, as it is the first number in the math equation
' " " = simply puts a 'space' between first value and the symbol
' selSymbol = a simple function for getting the right symbol to display
' This relates back to our 'universal' variable established at the
' start of this Sub. Here is one reason for the esablishment of that
' as a universal value. If not universal, then we'd be passing our
' parameter all over again.
rtxShowWork.AppendText(result & " " & selSymbol() & " " & txtInput.Text.ToString)
' Now, we begin to do the actual math (for more information, see selMath sub below)
result = selMath()
' Now, we display our new results to the user
lblResult.Text = result.ToString
' Also show this result in a manner to complete the last line of math in our RichTextBox
rtxShowWork.AppendText(" = " & result.ToString)
' Here we add a 'line break' to our RichTextBox for the purpose of preparing it for the next line of math
rtxShowWork.AppendText(Environment.NewLine)
End If
' Finally, clear our input TextBox and reset its focus
txtInput.Text = ""
txtInput.Focus()
End Sub
''' <summary>
''' This is the first simple function referred to in the last Sub Routine.
''' It makes use of the previously established universal value based off of
''' our math enum.
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Function selSymbol() As String
' A SelectCase Statement is a good way to clean up long, nasty IfElse Statements
' This statement returns a string value representing the symbol of the calculation
' established by our universal 'calcValue'
Select Case calcValue
Case calc.Add
Return "+"
Case calc.Subtract
Return "-"
Case calc.Multiply
Return "*"
Case calc.Divide
Return "/"
End Select
' It's always good practice to end your function with a final return, so that if no
' other values are returned, it has a final result of some establishment
' Altho, not having a final return is not bad, as the final return will generally
' be the same thing as Return Nothing
Return Nothing
End Function
''' <summary>
''' Here, we make further use of our universal calcValue to determine which
''' math function to use on our 2 universal number values. Perhaps it should be
''' noted that, while we did not explicitly pass our new Text to a universal value,
''' reading the textbox before its been cleared can still be considered a universal
''' value for the second number in our math equation.
''' </summary>
Function selMath() As Double
' A Simple SelectCase Statement like in the previous Function,
' however, this time we will return the result of one of
' the previously established math functions.
' Of course, what result we return is based on the current case
' of our universal calcValue property.
Select Case calcValue
Case calc.Add
Return mAdd(result, txtInput.Text.ToString)
Case calc.Subtract
Return mSubtract(result, txtInput.Text.ToString)
Case calc.Multiply
Return mMultiply(result, txtInput.Text.ToString)
Case calc.Divide
Return mDivide(result, txtInput.Text.ToString)
End Select
End Function
#End Region
End Class
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|