TheVB10Guy TheVB10Guy - 3 months ago 26
Vb.net Question

PEMDAS Visual Basic

EDIT 2:
*fixed some grammar and made it easier to understand.

I need help on building a PEMDAS application in vb.net. I want it to solve an inputted equation like this for example: 4 – 3(4 –2(6 – 3)) ÷ 2. I am trying to make it so that when input something into a text box and then click a button it will display the answer of that equation on a label. I first tried coding the section for looking for the parentheses, but it didn't work. I'm trying to make the program look for parentheses inside the equation and then depending on what the operator is inside of the parentheses, it will add, subtract, divide, or multiply the two numbers inside. My code is :

Public Class Form1

Private Property ValidChars As String

Private Property Num2 As Object

Private Property Num1 As Object

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ValidChars = ("()")
If TextBox1.Text = ValidChars Then
TextBox1.Text() = Num1 + Num2
End If
End Sub
End Class


Any help will be well appreciated.

Thanks, bye!

EDIT 1
*sorry forgot to include first edit...

I need help on building a PEMDAS application in vb.net. I want it to solve an inputted equation like this for example: 4 – 3(4 –2(6 – 3)) ÷ 2. I am trying to make it so that when input something into a text box and then click a button it will display the answer of that equation on a label. I first tried coding the section for looking for the parentheses, but it didn't work. I'm trying to make the program look for parentheses inside the equation and then depending on what the operator is inside of the parentheses, it will add, subtract, divide, or multiply the two numbers inside. My code is :

Public Class Form1

Private Property ValidChars As String

Private Property Num2 As Object

Private Property Num1 As Object

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ValidChars = ("()")
If TextBox1.Text = ValidChars Then
TextBox1.Text() = Num1 + Num2
End If
End Sub
End Class


Any help will be well appreciated.

Thanks, bye!

Answer

This should be what you're looking for. This built-in function has its limits especially if the expression involves trigonometric functions but this should be enough for your needs.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim answer = New DataTable().Compute(TextBox1.Text, Nothing)
        MsgBox(answer)
    Catch ex As Exception
        MsgBox("Syntax Error")
    End Try
End Sub

If you want a more challenging approach, which I recommend you would, you can create your own algorithm to manipulate strings and get numbers within to solve the expression. String manipulation functions should be what you'll ever need such as Mid, Split, Contains, etc.

Comments