2
Dim equation As String
Dim numbers() As String
Dim operators As New List(Of String)
Dim result As Double
Dim rx As New Regex("(\+|\-|\*)+")
Dim matches As MatchCollection

equation = TextBox1.Text
numbers = equation.Split(New String() {"+"c, "-"c, "*"c}, StringSplitOptions.None)
matches = rx.Matches(equation)

Dim m1 As Match

For Each m1 In matches
    operators.Add(m1.Value)
Next

result = CInt(numbers(0))
Dim i As Integer

For i = 1 To numbers.GetUpperBound(0)
    Select Case operators(i - 1)
        Case "*"
            result *= CDec(numbers(i))
        Case "+"
            result += CDec(numbers(i))
        Case "-"
            result -= CDec(numbers(i))
        Case " ^"
            result ^= CDec(numbers(i))
    End Select
Next
MessageBox.Show(result)

That's my code, for example "1+4+2*3" how can i edit my code to start with the multiplication first and division then + and - . Does someone have an idea?

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
gew
  • 23
  • 2
  • 1
    Use parentheses - `(2*3)+1+4`. Note you'll have to figure out where best to use parantheses so you don't affect the outcome, but `(` and `)` have a higher precendence. [Operator Precedence in Visual Basic](http://msdn.microsoft.com/en-us/library/fw84t893.aspx) – Tim Nov 06 '14 at 09:21
  • how can i add them in my code and start with them? – gew Nov 06 '14 at 09:27

1 Answers1

0

I am adding mXparser math parser library, which is written in C#, but is CLS compliant - it can be easily used with VB. Please follow mXparser Hello World tutorial for VB.

Dim e As Expression = New Expression("2+(3-sin(pi))")
mXparser.consolePrintln( e.calculate() )

Regards

Leroy Kegan
  • 1,156
  • 10
  • 9