Reputation: 399
I'm creating a calculator in VB.net and I'm trying to get it so when a user enters a number it gets stored to a variable and then when they click a maths operator like a "+" it gets stored in a char variable and I know how to do that but when I do it and then print it out to a text box the actual sum itself, so for example
Dim num as integer = 1
Dim operator as char = "+"
txtbox.text = num & operator & num
which just prints 1 + 1 to the text box but I want it so it does the sum so then the user is able to use whatever math operator which then gets stored in a char value and then does the sum which then gets printed out to the text box.
Upvotes: 0
Views: 354
Reputation: 43743
There is no built-in method in VB.NET for evaluating mathematical equations which are stored in a string. In order to do something like that, you'd need to write your own expression-tree parser and then evaluate the expression-tree. That's a fairly complicated thing to do, especially for beginners. Therefore, when it's an important feature to support, most people resort to using an existing expression-evaluator library such as NCalc, so as to not reinvent the wheel. Another popular option is to use the CodeDom stuff in VB.NET to construct the expression as a .NET method which returns the resulting values, compile it to an in-memory assembly, and then execute the method to get the result.
However, in a case like this, where you are the one constructing the expression, it seems silly to first construct it into a string to just turn around and parse it back out into an expression tree again. It would be much simpler to either build the expression tree directly as the buttons of the calculator are clicked, or to immediately perform the operations and not save the expression at all.
Upvotes: 1
Reputation: 1148
write this way:
Select Case operator
case "+"
txtbox.text = num + num
case "-"
txtbox.text = num - num
End Select
Upvotes: 1