VB.NET Calculator

Associate
Joined
6 Dec 2007
Posts
2,103
Hi guys, you're probably going to to laugh at this, but I've gone wrong somewhere in my code for a calculator.

Basically, it'll add two or more numbers if you do something like 2 + 2 + 2 = 6, but if you do something like (2 + 2), and then hit equals to get 4, and then add 2 to that, It'll give some silly results. I think it's my equals button that is messed up, but I can't be sure.

Can anyone help? Will post snippets of code as required. Thanks :)
 
Code? Its hard to see whats wrong without seeing the code behind it.
 
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click

firstNum = firstNum + Convert.ToDecimal(txtNumbers.Text)

txtNumbers.Clear()

End Sub

Private Sub cmdEquals_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEquals.Click

secondNum = firstNum + Convert.ToDecimal(txtNumbers.Text)
txtNumbers.Clear()
txtNumbers.Text = Convert.ToString(secondNum)

End Sub

This be the code for the add and equals buttons. Thanks guys, let me know if anything else is needed :)
 
Your Equals click method is setting secondNum, but this isn't being used by the Add click method.

I would have thought the problem lies in this.
 
Your Equals click method is setting secondNum, but this isn't being used by the Add click method.

I would have thought the problem lies in this.

Dont think its this.

secondNum is an equals total, firstNum is a totting up during the add process. Looks like you need to set firstNum to 0 after doing equals mate, should fix it i think.
 
What I would recommend is to have a variable called something like subTotal rather than firstNumber and secondNumber.

When you click on any of the operator buttons (+, -, *, /) it assigns the current value on screen to the subTotal if it hasn't previously been assigned and sets a current operator value based on which operator you have clicked.
You would also need to set something which lets you type a new number without adding on to the previous number.
Then clicking on = takes the value in subTotal and performs the current operator action based with the numbe on screen.
Then you would also need to update the subTotal value.

e.g.

1) Click 4. Set subTotal to 4.
2) Click +. Set current operator to +
3) Click 5. Value on screen changes to 5.
4) Click =. Current operator is +, subTotal is 4 and value on screen is 5. Calculate 4+5 and display. This now sets the subTotal value to 9.
5) Click /. Set current operator to /
6) Click 3. Value on screen changes to 3.
7) Click =. Current operator is /, subTotal is 9 and value on screen is 3. Calculate 9/3 and display. This now sets the subTotal value to 3.

You could encapsulate all of this logic in a separate class as well so you're keeping it away from the stuff that controls the screen and buttons.
 
Back
Top Bottom