Your concept of how to parse the calculator text seems a little strange
If CalculatorText.Text.Contains("-") Then
Substract = CalculatorText.Text.Split("-")
For Each NumToPower As String In Substract
num -= CStr(NumToPower)
Next
End If
Firstly,
NumToPower
is already a String so there is no need for
Cstr(NumToPower). CStr is very old-school anyway - if you really do want to convert things to strings use
Convert.ToString()
instead.
You are trying to add a string to a long - that is bad practice, you might get away with it sometimes in VB but not always. You need to convert
NumToPower
to a Long.
Use
Long.Parse
or better,
Long.TryParse
. Here's the reference information
Parsing Numeric Strings in .NET | Microsoft Docs[
^]
Now step through what actually happens, either on paper or in your debugger.
As you hit this block of code
num
= 0,
NumToPower
is going to get the value 8 first, so your code says
num -= 8
which equals
-8
On the next pass,
NumToPower
= -2 so
num -=2
is the same as
-8-2
which equals -10
Basically, your logic of how to apply the operators to the numbers is incorrect.
Also consider the calculator text
8 - 2 + 4
Your logic will first split that on the + sign and you will get two items in the array "8 - 2" and "4" - when you try to convert that first one to a numeric value you are going to get an error.
You need to rethink how to parse the calculator string to get the numbers and operators out of it I'm afraid
Edit - I found a couple of helpful articles here on CodeProject
Here is a simple example that you could emulate ..
A Simple Calculator in Windows Forms[
^]
Or if you want to do a more complicated level of parsing the entire input string have a look at
Parsing Mathematical Expressions in VB.NET: Mission Possible[
^]