|
-
Feb 6th, 2007, 11:01 PM
#1
Thread Starter
Addicted Member
[RESOLVED] [2005] Best way to do this simple number addition/substraction
Hi,
I am reading lines from a text file.
80+15
90-12
etc.
For each line I am extracting two integers.
From the first line,
CLn will be 80
CLa will be 95
From the second line,
CLn will be 90
CLa will be 78
I got it working like this
arrLine(10).Trim is the dynamic text that can be num1+num2 or num1-num2
VB Code:
Dim cl As String = arrLine(10).Trim
Dim clN As Integer = 0
Dim clA As Integer = 0
Dim arr As String() = cl.Split("+")
clN = arr(0).Split("-")(0)
clA = clN
If arr.Length > 1 Then
clA = clN + arr(1)
Else
arr = cl.Split("-")
If arr.Length > 1 Then
clA = clN - arr(1)
End If
End If
Console.WriteLine (cl.ToString & " is " & clN.ToString & " and " & cla.ToString)
I find this "overcomplicating" a simple task and would like to ask how to do it more effectively may be using some .NET functions I am unaware of.
Thanks,
McoreD
-
Feb 7th, 2007, 01:18 AM
#2
Member
Re: [2005] Best way to do this simple number addition/substraction
Assuming you are only going to perform the math on two digits:
Code:
Dim cl As String = arrLine(10)
Dim clA As Integer = 0
'Split the string into individual digits held in arr(0) and arr(1)
Dim arr As String() = cl.Split("+"c, "-"c)
'Perform the appropriate math function based on the operator
Select Case cl.Substring(arr(0).Length, 1)
Case "+"
clA = Val(arr(0)) + Val(arr(1))
Case "-"
clA = Val(arr(0)) - Val(arr(1))
End Select
Console.WriteLine("Answer:" & clA.ToString)
I only showed addition and subtraction, but can easily be expanded with other operators. Also won't work with negative numbers.
If this doesn't work, provide some more info about the different situations you might encounter and I'll tweak the code.
Greg
Last edited by ghall426; Feb 7th, 2007 at 01:37 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|