Calculator - Cannot add/subtract/multiply by 0

I cannot add, subtract or multiply by 0 in my VB.NET Calculator

Page 1 of 1

13 Replies - 3366 Views - Last Post: 12 January 2011 - 07:03 PM Rate Topic: ***** 1 Votes

#1 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 11:00 AM

:helpsmilie:

I have built a small VB.NET Calculator but whenever I add, subtract or multiply by 0 the answer is always 0. Here is my code:
Spoiler


Any suggestions? :/

This post has been edited by AdamSpeight2008: 11 January 2011 - 01:15 PM
Reason for edit:: Putting Code inside Spoiler Tags


Is This A Good Question/Topic? 0
  • +

Replies To: Calculator - Cannot add/subtract/multiply by 0

#2 demausdauth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 635
  • Joined: 03-February 10

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 12:15 PM

Without changing everything....
First off I would replace + with & in your number button clicks.
Second in here..

    Private Sub ButtonPlus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPlus.Click
        'DRAFT
        If CInt(True) Then
            If FirstNumber = Nothing Then
                FirstNumber = Val(txtDisplay.Text)
                ProcessType = "+"
                numend = True
            Else
                If SecondNumber = Nothing Then
                    SecondNumber = Val(txtDisplay.Text)
                    Calculate()
                    FirstNumber = AnswerNumber
                    AnswerNumber = Nothing
                    ProcessType = "+"
                    txtDisplay.Text = FirstNumber
                    numend = True
                Else
                    ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show("An error has occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If
        End If
    End Sub




There is no point to this line If CInt(True) Then, it's either going to always be true or always be false. Just get rid of it.

I would re-examine your logic -- this appears to be a calculator of 2 numbers.

2 + 2 =
2 - 2 =
2 * 2 =
2 / 2 =

In all these processes the FirstNumber should be set when you click the operation (+,-,*,/) -- the operation routine should not handle the second number nor care about it. The equals operation should handle setting the second number if and only if the first number has already been set. Then it should perform the calculations. No place else should do the calculations based on the requirements that I read from your code.

The number button click events should just concatenate the text you don't need to check for 0. The 0 button is the only one that you should make a check for a blank, unless you want to allow prefixing with 0's (highly unlikely though).

Not sure of the purpose of numend, you should know that the number is finished being entered when the user either clicks an operation button (+,-,*,/) or when they click equals (=). That should indicate that the first or second number has been fully entered.

Sorry if this seems to be rather scathing.... but it is a few of the observations that I have made.
Was This Post Helpful? 0
  • +
  • -

#3 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 12:33 PM

View Postdemausdauth, on 11 January 2011 - 11:15 AM, said:

Without changing everything....
First off I would replace + with & in your number button clicks.
Second in here..

    Private Sub ButtonPlus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPlus.Click
        'DRAFT
        If CInt(True) Then
            If FirstNumber = Nothing Then
                FirstNumber = Val(txtDisplay.Text)
                ProcessType = "+"
                numend = True
            Else
                If SecondNumber = Nothing Then
                    SecondNumber = Val(txtDisplay.Text)
                    Calculate()
                    FirstNumber = AnswerNumber
                    AnswerNumber = Nothing
                    ProcessType = "+"
                    txtDisplay.Text = FirstNumber
                    numend = True
                Else
                    ComponentFactory.Krypton.Toolkit.KryptonMessageBox.Show("An error has occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If
        End If
    End Sub




There is no point to this line If CInt(True) Then, it's either going to always be true or always be false. Just get rid of it.

I would re-examine your logic -- this appears to be a calculator of 2 numbers.

2 + 2 =
2 - 2 =
2 * 2 =
2 / 2 =

In all these processes the FirstNumber should be set when you click the operation (+,-,*,/) -- the operation routine should not handle the second number nor care about it. The equals operation should handle setting the second number if and only if the first number has already been set. Then it should perform the calculations. No place else should do the calculations based on the requirements that I read from your code.

The number button click events should just concatenate the text you don't need to check for 0. The 0 button is the only one that you should make a check for a blank, unless you want to allow prefixing with 0's (highly unlikely though).

Not sure of the purpose of numend, you should know that the number is finished being entered when the user either clicks an operation button (+,-,*,/) or when they click equals (=). That should indicate that the first or second number has been fully entered.

Sorry if this seems to be rather scathing.... but it is a few of the observations that I have made.


Thanks for your post. I've done most of your suggestions.

This was actually meant to be a calculator for more than 2 numbers - that was why I handled SecondNumber in the operations (+, -, X, /). I think I've just confused things. Is there a different way I should handle this?

The purpose of numend is to make it that the number it still shown after you click +, - etc. until you enter a number.

I still have problems with adding, subtracting and multiplying by 0 (the answer is always 0). What should I do? :helpsmilie:
Was This Post Helpful? 0
  • +
  • -

#4 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2240
  • View blog
  • Posts: 9,410
  • Joined: 29-May 08

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 01:24 PM

Don't you tired of typing in essential the same code for each digit?
Do you know about methods (ie Functions and Subroutines)?


You've got ~10 methods doing the basically the same thing. Did you copy and paste the first one and then altered it?
If txtDisplay.Text = "Error" Then Exit Sub
If txtDisplay.Text = "0" Then
  txtDisplay.Text = ""
  txtDisplay.Text = "1"
Else
  If numend = True Then
    txtDisplay.Text = ""
    txtDisplay.Text = "1"
    numend = False
    Exit Sub
  End If
  txtDisplay.Text = txtDisplay.Text + "1"
End If



Public Sub SomeAppropiateName(digit As String)
If txtDisplay.Text = "Error" Then Exit Sub
If txtDisplay.Text = "0" Then
  txtDisplay.Text = ""
  txtDisplay.Text = digit
Else
  If numend = True Then
    txtDisplay.Text = ""
    txtDisplay.Text = Digit
    numend = False
    Exit Sub
  End If
  txtDisplay.Text = txtDisplay.Text & Digit
End If
End Sub



Each button now is just a call the this method. At lot easier to read.
Was This Post Helpful? 0
  • +
  • -

#5 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 01:46 PM

View PostAdamSpeight2008, on 11 January 2011 - 12:24 PM, said:

Don't you tired of typing in essential the same code for each digit?
Do you know about methods (ie Functions and Subroutines)?


You've got ~10 methods doing the basically the same thing. Did you copy and paste the first one and then altered it?
If txtDisplay.Text = "Error" Then Exit Sub
If txtDisplay.Text = "0" Then
  txtDisplay.Text = ""
  txtDisplay.Text = "1"
Else
  If numend = True Then
    txtDisplay.Text = ""
    txtDisplay.Text = "1"
    numend = False
    Exit Sub
  End If
  txtDisplay.Text = txtDisplay.Text + "1"
End If



Public Sub SomeAppropiateName(digit As String)
If txtDisplay.Text = "Error" Then Exit Sub
If txtDisplay.Text = "0" Then
  txtDisplay.Text = ""
  txtDisplay.Text = digit
Else
  If numend = True Then
    txtDisplay.Text = ""
    txtDisplay.Text = Digit
    numend = False
    Exit Sub
  End If
  txtDisplay.Text = txtDisplay.Text & Digit
End If
End Sub



Each button now is just a call the this method. At lot easier to read.


Thanks I'll do that.

Do you have any idea about my calculator not being able to add, subtract or multiply by 0?
Was This Post Helpful? 0
  • +
  • -

#6 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2240
  • View blog
  • Posts: 9,410
  • Joined: 29-May 08

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 02:00 PM

Have you tried learning some basic debugging skills?
Was This Post Helpful? 0
  • +
  • -

#7 demausdauth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 635
  • Joined: 03-February 10

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 02:21 PM

First thing I would do is for each of your number button --set the .Tag property to the individual number. So for the 0 button the .Tag property would be 0, etc... Then you can use the following click event for each of the number buttons. You could probably just use the text of the button itself, but let's say that you want to use an image on the button instead... well then you would have to rewrite code, this way it's done.


Public Sub NumberButtonclickEvent(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click, button2.Click, button3.Click, button4.Click, button5.click, button6.click, button7.click, button8.Click, button9.Click, button0.click

     Dim tempButton As Button = DirectCast(sender, Button)

     Dim buttonclicked As Integer = Convert.ToInteger(tempButton.Tag.ToString())

     If buttonclicked = 0 Then
          If Not String.IsNullOrEmpty(txtDisplay.Text.Trim()) Then
               'do not add the zero to the display
               ' this prevents a number having preceeding 0's example: 003
               Exit Sub
          End If     
     End If

     txtDisplay.Text &= buttonclicked.ToString()

End Sub



Second I would use an List or an array to hold the numbers that are going to be operated on. So declare a class level variable. Also I would use a List or an array to hold the operations, since you wanted to do many.
Public Class Calculator2
     
     List(Of Double) _numbers = new List(Of Double)()
     List(Of String) _operations = new List(Of String)()

     'etc...
     'etc...
End Class



Now I would put all the operations into one click event also. This involves that .Tag property again for the operation buttons.

Public Sub OperationButtonclick(ByVal sender As Object, ByVal e As EventArgs) Handles buttonplus.click, buttonminus.click, buttontimes.click, buttondivide.click


     'Check for a value in the display first
     If String.IsNullOrEmpty(txtDisplay.Text.Trim()) Then Exit Sub


     Dim clickedButton As Button = DirectCast(sender, Button)

     'Since the only way to get a number into the display is through the buttons then we know that there
     ' cannot be any errorneous values such as characters 'abcd'
     'Add the current number in the display to the list of numbers
     Dim currentNumber As Double = Double.Parse(txtDisplay.Text.Trim())
     _numbers.Add(currentNumber)
     
     'Add the operation to the operations
     _operations.Add(clickedButton.Tag.ToString())

     'Clear the display to be ready for the next entry
     txtDisplay.Text = String.Empty
End Sub



The equals button will need to perform the calculations and it should also get the last number entered. And you can decide how you want to handle an equals without an entered number. Either it will require a number to be entered previous to performing calculations or it will need to determine if it just needs to remove the last operation performed.

Public Sub EqualsButtonclicked(ByVal sender As Object, ByVal e As EventArgs) Handles equals.Click
     
     'Do nothing if:
     '     The current entry is empty,blank and there has been only 1 number or 1 operation added
     '     there is no operations added
     
     If String.IsNullOrEmpty(txtDisplay.Text.Trim()) OrElse 
          _numbers.Count < 2 OrElse
          _operations.Count < 2 Then Exit Sub

     'Should be valid (I could have forgotten something, double check the logic)
     'Now we need to add the last number to the list of numbers.
     _numbers.Add(Double.Parse(txtDisplay.Text.Trim()))

     'perform the calculations
     Calculate()    

End Sub



The meat of the program....

Public Sub Calculate()

     'need to loop through our numbers and perform operations against them.

     Dim answer As Double = 0
     Dim numberIndex = 0


    
     For Each operation As String in _operations
         
          Dim firstNumber As Double
          Dim secondNumber As Double
          

          firstNumber = _numbers(numberIndex)
          
          'increment the number index
          numberIndex += 1

          'Check to see if we should get the secondNumber from the 
          ' list of numbers or re use the answer we got from a previous
          ' operation
          If numberIndex > 2
               secondNumber = answer
          Else
               secondNumber = _numbers(numberIndex)
               numberIndex += 1
          End If

          Select Case operation
               Case "+":
                    answer = firstNumber + secondNumber

               Case "-":
                    answer = secondNumber - firstNumber

               Case "*":
                    answer = firstNumber * secondNumber

               Case "/":
                    answer = secondNumber / firstNumber

          End Select
     Next

     'Display the answer
     txtDisplay.Test = answer.ToString()

End Sub



By far this isn't completed, it doesn't handle a lot of errors that could crop up and actually it really would only work well for the first time you do calculations. You will need to setup a reset method to clear the previous round of calculations. Also you should look into learning how to use the debugger, that will come in quite handy.
Was This Post Helpful? 1
  • +
  • -

#8 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2240
  • View blog
  • Posts: 9,410
  • Joined: 29-May 08

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 02:27 PM

You do know the event handler (the method that handle the event) can be used by multiple controls?

Extract from my implementation of a calculator.
 Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles B0.Click,
    B1.Click, B2.Click, B3.Click, B4.Click, B5.Click, B6.Click, B7.Click, B8.Click, B9.Click, DecPoint.Click,
    B11.Click, B12.Click, B13.Click, B14.Click, B15.Click, Equal.Click, Recip.Click, Delete.Click, ClearEntry.Click,
    ClearAll.Click, SqRoot.Click
    Dim clicked_button As Button = TryCast(sender, Button)
    If clicked_button IsNot Nothing Then DoTh(clicked_button.Text)
  End Sub

Was This Post Helpful? 0
  • +
  • -

#9 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 11 January 2011 - 03:00 PM

Thanks for all the comments. I'll look into them. I'll post the results once I've done (possibly several hours - I'm tired! :sleep1:)
Was This Post Helpful? 0
  • +
  • -

#10 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 12 January 2011 - 09:55 AM

I've done what you said and it works great! Thank you! Just for future reference...

View Postdemausdauth, on 11 January 2011 - 01:21 PM, said:


Public Sub NumberButtonclickEvent(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click, button2.Click, button3.Click, button4.Click, button5.click, button6.click, button7.click, button8.Click, button9.Click, button0.click

     Dim tempButton As Button = DirectCast(sender, Button)

     Dim buttonclicked As Integer = Convert.ToInteger(tempButton.Tag.ToString())

     If buttonclicked = 0 Then
          If Not String.IsNullOrEmpty(txtDisplay.Text.Trim()) Then
               'do not add the zero to the display
               ' this prevents a number having preceeding 0's example: 003
               Exit Sub
          End If     
     End If

     txtDisplay.Text &= buttonclicked.ToString()

End Sub



Dim buttonclicked As Integer = Convert.ToInteger(tempButton.Tag.ToString())



should be

Dim buttonclicked As Integer = Convert.ToInt32(tempButton.Tag.ToString())



View Postdemausdauth, on 11 January 2011 - 01:21 PM, said:

Public Class Calculator2
     
     List(Of Double) _numbers = new List(Of Double)()
     List(Of String) _operations = new List(Of String)()

     'etc...
     'etc...
End Class



It should be:

Dim _numbers As List(Of Double) = New List(Of Double)
Dim _operations As List(Of String) = New List(Of String)



I'm using Visual Basic.NET. ;)

View Postdemausdauth, on 11 January 2011 - 01:21 PM, said:

Public Sub EqualsButtonclicked(ByVal sender As Object, ByVal e As EventArgs) Handles equals.Click
     
     'Do nothing if:
     '     The current entry is empty,blank and there has been only 1 number or 1 operation added
     '     there is no operations added
     
     If String.IsNullOrEmpty(txtDisplay.Text.Trim()) OrElse 
          _numbers.Count < 2 OrElse
          _operations.Count < 2 Then Exit Sub

     'Should be valid (I could have forgotten something, double check the logic)
     'Now we need to add the last number to the list of numbers.
     _numbers.Add(Double.Parse(txtDisplay.Text.Trim()))

     'perform the calculations
     Calculate()    

End Sub



Maybe I'm wrong but shouldn't

If String.IsNullOrEmpty(txtDisplay.Text.Trim()) OrElse 
          _numbers.Count < 2 OrElse
          _operations.Count < 2 Then Exit Sub



be

If String.IsNullOrEmpty(txtDisplay.Text.Trim()) OrElse 
          _numbers.Count < 2 OrElse
          _operations.Count < 1 Then Exit Sub



?

View Postdemausdauth, on 11 January 2011 - 01:21 PM, said:

Public Sub Calculate()

     'etc...

          Select Case operation
               Case "+":
                    answer = firstNumber + secondNumber

               Case "-":
                    answer = secondNumber - firstNumber

               Case "*":
                    answer = firstNumber * secondNumber

               Case "/":
                    answer = secondNumber / firstNumber

          End Select
     Next

     'Display the answer
     txtDisplay.Test = answer.ToString()

End Sub



Important thing here - what if the calculation was just a 2 number calculation? The second number in - and / calculations would therefor not be the correct answer and you'd be subtracting/dividing the numbers the wrong way. Maybe this would work?

Select Case operation
               Case "+":
                    answer = firstNumber + secondNumber

               Case "-":
                    If numberIndex = 2 OrElse numberIndex > 2 Then
                         answer = secondNumber - firstNumber
                    Else
                         answer = firstNumber - secondNumber
                    End If
               Case "*":
                    answer = firstNumber * secondNumber

               Case "/":
                    If numberIndex = 2 OrElse numberIndex > 2 Then
                         answer = secondNumber / firstNumber
                    Else
                         answer = firstNumber / secondNumber
                    End If
          End Select



Thanks again for the comment - you're a hero! :D

I'll posy my code (in spoiler tags) below in case would like a calculator ;)

This post has been edited by Bo98: 12 January 2011 - 09:56 AM

Was This Post Helpful? 0
  • +
  • -

#11 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 12 January 2011 - 10:02 AM

Spoke too soon! The equals button doesn't work.

Here's my code:

Spoiler

This post has been edited by Bo98: 12 January 2011 - 10:02 AM

Was This Post Helpful? 1
  • +
  • -

#12 demausdauth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 635
  • Joined: 03-February 10

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 12 January 2011 - 12:44 PM

I did not create a project for this -- so that does explain the syntax errors ( I mostly work in C# right now) and you are correct about the logic errors.

I'm curious by what you mean it doesn't work.
Was This Post Helpful? 0
  • +
  • -

#13 Bo98  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 11-January 11

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 12 January 2011 - 01:05 PM

When I press equals nothing seems to happen.
Was This Post Helpful? 0
  • +
  • -

#14 demausdauth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 175
  • View blog
  • Posts: 635
  • Joined: 03-February 10

Re: Calculator - Cannot add/subtract/multiply by 0

Posted 12 January 2011 - 07:03 PM

Set a breakpoint?? See what is happening in the event.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1