Results 1 to 3 of 3

Thread: [VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator

  1. #1

    Thread Starter
    Addicted Member spyk3's Avatar
    Join Date
    Apr 2009
    Location
    Dothan, AL
    Posts
    218

    [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:
    1. ''' <summary>
    2. ''' EZ Calc Tutorial
    3. ''' JD McKinstry
    4. ''' First, it should be noted, as you become a
    5. ''' more experienced coder, you will find this tutorial
    6. ''' to contain very simple, non-standard practices. The
    7. ''' purpose of this is not to teach you to be company ready,
    8. ''' it is simply to teach some very basic examples of the
    9. ''' Basic Coding Language. Should you find this tutorial
    10. ''' beneath your skillset, then I advise you check out MicroSoft's
    11. ''' Developer Studio online and look up the Intermidiate Tutorials.
    12. ''' </summary>
    13. Public Class frmMain
    14.  
    15.     ' This is simply the establishment of a Region
    16.     ' Regions are useful in dividing up sections of code into similar catagories
    17.     ' This is not extremely important for now, but helps to break down the compacted view,
    18.     ' making it easier to see all the items in your code.
    19. #Region "   Vars/Properties     "
    20.  
    21.     ''' <summary>
    22.     ''' First things first, to do simple XML Comments like this one,
    23.     ''' Simply place cursor 1 line above the method, property, or variable
    24.     ''' you wish to document/comment on. Then simply type 3 single quotes;
    25.     ''' such as the ones you see at the beggining of each line here.
    26.     ''' In Visual Studio, this will automatically create a simple XML
    27.     ''' Document/Comment layout!
    28.     ''' This is useful later, when looking at your Object Library, as each
    29.     ''' section in these comments is shown in an easy to read manner.
    30.     ''' </summary>
    31.     ''' <remarks>Notice, it doesn't add all featues, such as the 'example' feature seen below!</remarks>
    32.     ''' <example>ezXML_Documentation = "This is a String"</example>
    33.     Private ezXML_Documentation As String
    34.  
    35.     ''' <summary>
    36.     ''' Establish Enumerable for the 4 basic calculations.
    37.     ''' This will later be used to determine which function
    38.     ''' to use as your program "calculates"
    39.     ''' </summary>
    40.     Enum calc
    41.         Add
    42.         Subtract
    43.         Multiply
    44.         Divide
    45.     End Enum
    46.  
    47.     ''' <summary>
    48.     ''' This is a pre-.Net 4.0 standard for establishing a
    49.     ''' "root variable" for later established properties.
    50.     ''' This gives the Properties a variable to use for
    51.     ''' interaction.
    52.     ''' </summary>
    53.     Private _result As Double
    54.     Private _calcValue As calc
    55.  
    56.     ''' <summary>
    57.     ''' These are both public properties which will be
    58.     ''' used when 'doing the work' behind this calc program.
    59.     ''' This first property is simply used to maintain the value
    60.     ''' of our final result for each calcullation.
    61.     ''' </summary>
    62.     Public Property result() As Double
    63.         Get
    64.             Return _result
    65.         End Get
    66.         Set(ByVal value As Double)
    67.             _result = value
    68.         End Set
    69.     End Property
    70.     ''' <summary>
    71.     ''' This second property will be used to store the present
    72.     ''' value for the function being preformed. Remember our enum?
    73.     ''' As you notice this property is an establishment of that enum,
    74.     ''' meaning it can hold one value selected from that enum.
    75.     ''' </summary>
    76.     ''' <value></value>
    77.     ''' <returns></returns>
    78.     ''' <remarks></remarks>
    79.     Property calcValue() As calc
    80.         Get
    81.             Return _calcValue
    82.         End Get
    83.         Set(ByVal value As calc)
    84.             _calcValue = value
    85.         End Set
    86.     End Property
    87.  
    88. #End Region
    Last edited by spyk3; Jan 1st, 2011 at 02:54 PM.

  2. #2

    Thread Starter
    Addicted Member spyk3's Avatar
    Join Date
    Apr 2009
    Location
    Dothan, AL
    Posts
    218

    Re: [VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator

    EZ Calc Code Code:
    1. #Region "   Events      "
    2.  
    3.     ''' <summary>
    4.     ''' This will be the first event you will deal with for most simple programs.
    5.     ''' In Object Orientated Programing, events are used to help seperate the
    6.     ''' 'do work' value of the code behind from the code used to establish a visual.
    7.     ''' This event is triggered when the form is loaded and here, we simply want to
    8.     ''' give the input textbox focus.  This means, that whens the program loads,
    9.     ''' the cursor will already be placed in the textbox and the user can immidiately
    10.     ''' start typing in calculations.
    11.     ''' </summary>
    12.     ''' <param name="sender">This first parameter simply represents a 'sending' control.
    13.     ''' This simply means that the value of 'sender' will be the control that
    14.     ''' 'triggered the event'. This is usually the first parameter of form controller
    15.     ''' events, however, your first parameter may be anything the person who wrote
    16.     ''' the control or object establishes it to be. In other words, this is not always
    17.     ''' your first parameter.</param>
    18.     ''' <param name="e">In this case, this param is used to grab the 'message' passed
    19.     ''' as this event fires.  For more information, please see a more advanced tutorial,
    20.     ''' as the explination of this variable is simple beyond the scope of this simple tutorial.</param>
    21.     ''' <remarks></remarks>
    22.     Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    23.         txtInput.Focus()
    24.     End Sub
    25.  
    26.     ''' <summary>
    27.     ''' These 4 button events trigger whenever a 'math' button is clicked.
    28.     ''' As you will notice, I have very little code here, as it is simply better
    29.     ''' to come up with a 'universal' method for multiple controls doing 'similar'
    30.     ''' work. Of course, not all variables, or even the math is the same, but as
    31.     ''' you will later see in the method, we conquer this issue with universal variables.
    32.     ''' </summary>
    33.     Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
    34.         doWork(calc.Add)
    35.     End Sub
    36.     Private Sub btnDivide_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDivide.Click
    37.         doWork(calc.Divide)
    38.     End Sub
    39.     Private Sub btnMultiply_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnMultiply.Click
    40.         doWork(calc.Multiply)
    41.     End Sub
    42.     Private Sub btnSubtract_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubtract.Click
    43.         doWork(calc.Subtract)
    44.     End Sub
    45.  
    46.     ''' <summary>
    47.     ''' This event simply resets our form to ground zero. As you learn more,
    48.     ''' you'll note, there are multple ways to do this, but for now, I will
    49.     ''' simply show you the 'straight forward' approach. This means simply
    50.     ''' reseting each control on the form to its original value.
    51.     ''' As you will also notice, I don't 'reset' all controls. Simply put,
    52.     ''' not all controls contain a 'changing' value, and thus do not require a reset.
    53.     ''' </summary>
    54.     Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
    55.         '   First we reset our 2 properties
    56.         result = 0.0
    57.         calcValue = Nothing
    58.         '   Next we reset all 'changing visuals' on our form
    59.         '   In our case, this means 1 label, 1 textbox, and 1 richtextbox
    60.         lblResult.Text = "[Result]"
    61.         txtInput.Text = ""
    62.         rtxShowWork.Text = ""
    63.         '   Finally, reset the focus of the form to the input textbox
    64.         txtInput.Focus()
    65.         '   Tada! We are ready for our next set of calculations!
    66.     End Sub
    67.  
    68.     ''' <summary>
    69.     ''' Here will deal with 2 issues.
    70.     ''' First, if the user has pressed a calculation key, we dont want to display it
    71.     ''' in the textbox, but we do want it to do the work.  This event fires before
    72.     ''' any text is actually sent to the textbox, thus, here is a good place to catch
    73.     ''' errors key presses (such as typing in the letter 'U').
    74.     ''' Second, if the user types anything else that is not a calculation or number
    75.     ''' then we want to disreguard the key as it is usless to our current project.
    76.     ''' </summary>
    77.     Private Sub txtInput_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInput.KeyPress
    78.         '   Often times, Long IfElse Statements can be replaced with better practices
    79.         '   but here, I simply want to break down the work taking place
    80.         '   The first 4 parts of this if statement do 2 things
    81.         '       1st, if key pressed is a math symbol, then set the
    82.         '           e.Handled property to "true" so that it will not
    83.         '           be displyed in the text box
    84.         '       2nd, do the math associated with the key pressed
    85.         '   The last part of this statement simply stops anything that is not a
    86.         '       number from continueing onto the textbox
    87.         If e.KeyChar.ToString = "+" Then
    88.             e.Handled = True
    89.             doWork(calc.Add)
    90.         ElseIf e.KeyChar.ToString = "-" Then
    91.             e.Handled = True
    92.             doWork(calc.Subtract)
    93.         ElseIf e.KeyChar.ToString = "*" Then
    94.             e.Handled = True
    95.             doWork(calc.Multiply)
    96.         ElseIf e.KeyChar.ToString = "/" Then
    97.             e.Handled = True
    98.             doWork(calc.Divide)
    99.         ElseIf Not IsNumeric(e.KeyChar) Then
    100.             e.Handled = True
    101.         End If
    102.     End Sub
    103.  
    104. #End Region

  3. #3

    Thread Starter
    Addicted Member spyk3's Avatar
    Join Date
    Apr 2009
    Location
    Dothan, AL
    Posts
    218

    Re: [VS2008-][.Net 3.5-]A Real Beginners Guide to makeing a Simple Calculator

    EZ Calc Code Code:
    1. #Region "   Methods     "
    2.  
    3.     ''' <summary>
    4.     ''' Here i've established 4 very simple functions for preforming our
    5.     ''' 4 basic math calculations. A function is good for this, as we can
    6.     ''' pass in 2 variables and recieve an answer in return!
    7.     ''' </summary>
    8.     Private Function mAdd(ByVal frstValu As Object, ByVal scndValue As Object)
    9.         '   These first 2 variables ensre that our values passed in are in correct format for calculating
    10.         Dim tmpFrstValue As Double = CDbl(frstValu)
    11.         Dim tmpScndValue As Double = CDbl(scndValue)
    12.         '   This 3rd variable is our math!
    13.         '   Something to note about vb, when placed between 2 numeric values,
    14.         '       a math symbol (such as the 4 in this program) is translated
    15.         '       literally.
    16.         Dim tmpResult As Double = tmpFrstValue + tmpScndValue
    17.         '   This is a real difference between a Function and a Sub Routine.
    18.         '   Functions should always 'return' a value to the place where it's called.
    19.         '   However, a sub will only return ZERO values, as it simply 'does work'
    20.         Return tmpResult
    21.     End Function
    22.     Private Function mSubtract(ByVal frstValu As Object, ByVal scndValue As Object)
    23.         Dim tmpFrstValue As Double = CDbl(frstValu)
    24.         Dim tmpScndValue As Double = CDbl(scndValue)
    25.         Dim tmpResult As Double = tmpFrstValue - tmpScndValue
    26.         Return tmpResult
    27.     End Function
    28.     Private Function mMultiply(ByVal frstValu As Object, ByVal scndValue As Object)
    29.         Dim tmpFrstValue As Double = CDbl(frstValu)
    30.         Dim tmpScndValue As Double = CDbl(scndValue)
    31.         Dim tmpResult As Double = tmpFrstValue * tmpScndValue
    32.         Return tmpResult
    33.     End Function
    34.     Private Function mDivide(ByVal frstValu As Object, ByVal scndValue As Object)
    35.         Dim tmpFrstValue As Double = CDbl(frstValu)
    36.         Dim tmpScndValue As Double = CDbl(scndValue)
    37.         Dim tmpResult As Double = tmpFrstValue / tmpScndValue
    38.         Return tmpResult
    39.     End Function
    40.  
    41.     ''' <summary>
    42.     ''' This is our main Sub Routine. Here is where most of the 'work' happens
    43.     ''' after a calculation button is pressed. This is established to keep from
    44.     ''' having 'repetative' throughout each math button click.
    45.     ''' </summary>
    46.     ''' <param name="value">This is a prime example of a coder defined parameter.
    47.     ''' Keep in mind, when writing your own methods, you can establish as many
    48.     ''' parameters as you feel you will need.
    49.     ''' This parameter provides a simple way to help deteremine
    50.     ''' what math to perform, as that is the key difference between the
    51.     ''' objects using this method.</param>
    52.     Sub doWork(ByVal value As calc)
    53.         '   First, we set our universal 'what math' parameter,
    54.         '       so that is any other method should need to know
    55.         '       its value, we don't have to pass it as another parameter
    56.         calcValue = value
    57.         '   Next, before calculating anything, we need to make sure the
    58.         '       user ment to calculate somthing. This is accounting for user
    59.         '       error. This simple practice helps in every prgrom to prevent
    60.         '       such errors as trying to add 2 objects that are empty.
    61.         If Not txtInput.Text = "" Then
    62.             '   With the opening work out of the way, we start on the meat
    63.             '   1st, for our case, we'll display the math about to take place
    64.             '       in our RichTextBox
    65.             '       The text being shown is as follows
    66.             '           result = the current value of our result property, as it is the first number in the math equation
    67.             '           " " = simply puts a 'space' between first value and the symbol
    68.             '           selSymbol = a simple function for getting the right symbol to display
    69.             '               This relates back to our 'universal' variable established at the
    70.             '               start of this Sub.  Here is one reason for the esablishment of that
    71.             '               as a universal value. If not universal, then we'd be passing our    
    72.             '               parameter all over again.
    73.             rtxShowWork.AppendText(result & " " & selSymbol() & " " & txtInput.Text.ToString)
    74.             '   Now, we begin to do the actual math (for more information, see selMath sub below)
    75.             result = selMath()
    76.             '   Now, we display our new results to the user
    77.             lblResult.Text = result.ToString
    78.             '   Also show this result in a manner to complete the last line of math in our RichTextBox
    79.             rtxShowWork.AppendText(" = " & result.ToString)
    80.             '   Here we add a 'line break' to our RichTextBox for the purpose of preparing it for the next line of math
    81.             rtxShowWork.AppendText(Environment.NewLine)
    82.         End If
    83.         '   Finally, clear our input TextBox and reset its focus
    84.         txtInput.Text = ""
    85.         txtInput.Focus()
    86.     End Sub
    87.  
    88.     ''' <summary>
    89.     ''' This is the first simple function referred to in the last Sub Routine.
    90.     ''' It makes use of the previously established universal value based off of
    91.     ''' our math enum.
    92.     ''' </summary>
    93.     ''' <returns></returns>
    94.     ''' <remarks></remarks>
    95.     Function selSymbol() As String
    96.         '   A SelectCase Statement is a good way to clean up long, nasty IfElse Statements
    97.         '   This statement returns a string value representing the symbol of the calculation
    98.         '       established by our universal 'calcValue'
    99.         Select Case calcValue
    100.             Case calc.Add
    101.                 Return "+"
    102.             Case calc.Subtract
    103.                 Return "-"
    104.             Case calc.Multiply
    105.                 Return "*"
    106.             Case calc.Divide
    107.                 Return "/"
    108.         End Select
    109.         '   It's always good practice to end your function with a final return, so that if no
    110.         '       other values are returned, it has a final result of some establishment
    111.         '   Altho, not having a final return is not bad, as the final return will generally
    112.         '       be the same thing as Return Nothing
    113.         Return Nothing
    114.     End Function
    115.  
    116.     ''' <summary>
    117.     ''' Here, we make further use of our universal calcValue to determine which
    118.     ''' math function to use on our 2 universal number values. Perhaps it should be
    119.     ''' noted that, while we did not explicitly pass our new Text to a universal value,
    120.     ''' reading the textbox before its been cleared can still be considered a universal
    121.     ''' value for the second number in our math equation.
    122.     ''' </summary>
    123.     Function selMath() As Double
    124.         '   A Simple SelectCase Statement like in the previous Function,
    125.         '       however, this time we will return the result of one of
    126.         '       the previously established math functions.
    127.         '   Of course, what result we return is based on the current case
    128.         '       of our universal calcValue property.
    129.         Select Case calcValue
    130.             Case calc.Add
    131.                 Return mAdd(result, txtInput.Text.ToString)
    132.             Case calc.Subtract
    133.                 Return mSubtract(result, txtInput.Text.ToString)
    134.             Case calc.Multiply
    135.                 Return mMultiply(result, txtInput.Text.ToString)
    136.             Case calc.Divide
    137.                 Return mDivide(result, txtInput.Text.ToString)
    138.         End Select
    139.     End Function
    140.  
    141. #End Region
    142.  
    143. 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
  •  



Click Here to Expand Forum to Full Width