Hi y'all. I'm ultimately working towards a parser, but I figured that I'd start small and create an expression evaluator. This is what I have so far:
It allows the user to enter in an expression with however many spaces between the digits and the operators without the spacing being consistent. It follows PEMDAS, but what it does not account for is parenthesis which overrides PEMDAS and negative numbers. Right now as it sits, my code would produce a syntax error if the user attempted:
Because it would literally translate it to one plus minus one, which syntactically is invalid.
With this being the math forum, I figured that I'd ask it here. How would I account for those two issues?
Code:
Private operators() As String = {"-", "+", "/", "*", "^"}
Public Function EvaluateExpression(ByVal expression As String) As Double
For i As Integer = 0 To operators.Length - 1
'Chose an operator to check
Dim sign As String = operators(i)
'Get the last instance of the operator
Dim lastPosition As Integer = expression.LastIndexOf(sign)
If lastPosition > -1 Then
'If there's an instance of the operator, then begin the recursion
Dim part1 As String = expression.Substring(0, lastPosition - GetSpacesBefore(lastPosition, expression))
Dim part2 As String = expression.Substring((lastPosition + 1) + GetSpacesAfter(lastPosition, expression))
'Calculate the left and right part of the expression based on the operator
If sign = "-" Then
Return EvaluateExpression(part1) - EvaluateExpression(part2)
ElseIf sign = "+" Then
Return EvaluateExpression(part1) + EvaluateExpression(part2)
ElseIf sign = "/" Then
Return EvaluateExpression(part1) / EvaluateExpression(part2)
ElseIf sign = "*" Then
Return EvaluateExpression(part1) * EvaluateExpression(part2)
Else
Return EvaluateExpression(part1) ^ EvaluateExpression(part2)
End If
End If
Next
'There are no operators, return the value
Return CDbl(expression)
End Function
Private Function GetSpacesBefore(ByVal index As Integer, ByVal input As String) As Integer
Dim counter As Integer = 0
For x As Integer = index To 0 Step -1
If input(x) = " " Then
counter += 1
Else
Return counter
End If
Next
Return 0
End Function
Private Function GetSpacesAfter(ByVal index As Integer, ByVal input As String) As Integer
Dim counter As Integer = 0
For x As Integer = index To input.Length - 1
If input(x) = " " Then
counter += 1
Else
Return counter
End If
Next
Return 0
End Function
Code:
1 + -1
With this being the math forum, I figured that I'd ask it here. How would I account for those two issues?