Results 1 to 2 of 2

Thread: [RESOLVED] [2005] Best way to do this simple number addition/substraction

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Apr 2003
    Location
    Australia
    Posts
    252

    Resolved [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:
    1. Dim cl As String = arrLine(10).Trim
    2. Dim clN As Integer = 0
    3. Dim clA As Integer = 0
    4.  
    5. Dim arr As String() = cl.Split("+")
    6. clN = arr(0).Split("-")(0)
    7. clA = clN
    8.  
    9. If arr.Length > 1 Then
    10.     clA = clN +  arr(1)
    11. Else
    12.     arr = cl.Split("-")
    13.     If arr.Length > 1 Then
    14.         clA = clN - arr(1)
    15.     End If
    16. End If
    17.  
    18. 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

  2. #2
    Member
    Join Date
    Sep 2006
    Posts
    63

    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
  •  



Click Here to Expand Forum to Full Width