How to make calculations of a list of array elements

I have a file that contains weight , speed and radius data ...
i am suppose to calculate a force using that data.. and add them in a list box where it lists Weight,Speed,Radius, Force , i am having problems getting the force.. how can i do that ? i am getting in the list box the first 3 data on each line correctly.. but how can i do the calculations of that data ?? Also do you have any idea how i can add error handling .. because the file has some tricks like a name instead of a numerical value.. and a 0 in it.. which cannot be calculated and such...

Comments

  • seancampbellseancampbell Pennsylvania, USA
    Error handling examples:
    [code]

    Try
    Dim I as Integer = 0
    Dim H as Integer = 2 / I

    Catch ex as Exception
    'If this happens, then an error occurred, and execution stops happening
    MsgBox(ex.Message)
    End Try

    'An error will stop execution of a loop that is inside of it:

    Try
    Dim I as Integer = 4
    Dim H as Integer
    For H = -2 to 2
    I = I / H
    MsgBox(I)
    Next H
    Catch ex as exception
    MsgBox(ex.Message)
    End Try

    'You can use error handling inside a loop, but it makes the program execute much slower
    'If performance is an issue, using a Try Catch inside a loop might not be ideal

    Dim I as Integer
    For I = -4 to 4
    Try
    Debug.WriteLine(200/I)
    Catch ex as Exception
    Debug.WriteLine("Error!!!!!!!!")
    End try
    Next I
    [/code]
  • seancampbellseancampbell Pennsylvania, USA
    Dim Height() as Integer = {10, 20, 30, 25, 15}
    Dim Width() as Integer = {11, 22, 33, 44, 55}

    'Two arrays that are now equal length
    'I want to LOOP through the arrays and
    'write out the area of Height * Width

    Dim I as Integer

    'Height.Length returns an integer COUNT of all cells contained
    'in an array. The first cell is Height(0) and the last is Height(Height.Length - 1)
    Dim Area as Integer
    For I = 0 to Height.Length - 1
    Area = Height(I) * Width(I)
    Debug.WriteLine("Height " & Height(I) & " * Width " & Width(I) & " = are " & Area)
    Next I
    [/code]
  • Ok i am reading data from a file and the rendring the file with this code:

    Public Sub renderFile()
    Dim strLine As String
    Dim strFieldsArr(2) As String
    Dim sNdx As Single
    ' Clear the array contents
    Erase cTransArr
    sNdx = 0
    strLine = objStreamReader.ReadLine()
    While Not (strLine Is Nothing) ' As long as there is more data do...
    ReDim Preserve cTransArr(2, sNdx) ' Enlarge the array size by one more element
    strFieldsArr = strLine.Split(" ") ' Seperate the Date from the Amount... Based on Space seperation



    cTransArr(0, sNdx) = strFieldsArr(0) ' Save the Date...
    cTransArr(1, sNdx) = strFieldsArr(1)
    cTransArr(2, sNdx) = strFieldsArr(2) ' Save the Amount...
    strLine = objStreamReader.ReadLine() ' Read the next line from file...
    sNdx += 1 ' Increment the subscript.

    End While

    Try


    Dim strListLine As String
    lstbox.Items.Clear() ' Clear the ListBox contents
    For sNdx = 0 To cTransArr.GetUpperBound(1) ' Go through the array elements...
    If cTransArr(1, sNdx) <> 0 Then
    strListLine = String.Format("{0,-11}", cTransArr(0, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(1, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(2, sNdx))
    lstbox.Items.Add(strListLine) ' Add the formatted transaction to the listBox
    End If
    Next
    For sNdx = 0 To cTransArr.GetUpperBound(1)
    If cTransArr(2, sNdx) = 0 Then
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    Next
    Catch ex As InvalidCastException
    MessageBox.Show("Data Type Error..." & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Press OK to Continue", "Data Type Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try





    End Sub

    but it doesn't seem to work.. plus when i am trying to use this :
    formula:
    Force = ((weight * 2000) / 32) * (((mph * 1.466) * (mph * 1.466)) / radius)

    it doesn't seem to be working.. weight is cTransArr(0, sNdx) speed is cTransArr(1, sNdx) and radius is cTransArr(2, sNdx)

    i need to add if the force is higher then 50000 then it will list the results in the listbox
  • seancampbellseancampbell Pennsylvania, USA
    Any clues as to why this isn't working for you? What error message are you getting?
  • Ok i tried to edit as much as possible to make it work here are the problems i am having :

    - It is not giving me the exception error when it reads the zero..
    - It is stopping the calculations as soon as it reads the invalid value: Joe

    here is the code..

    [code] Public Sub renderFile()
    Dim strLine As String
    Dim strFieldsArr(2) As String
    Dim sNdx As Single
    ' Clear the array contents
    Erase cTransArr
    sNdx = 0
    strLine = objStreamReader.ReadLine()
    While Not (strLine Is Nothing) ' As long as there is more data do...
    ReDim Preserve cTransArr(2, sNdx) ' Enlarge the array size by one more element
    strFieldsArr = strLine.Split(" ") ' Seperate the Date from the Amount... Based on Space seperation



    cTransArr(0, sNdx) = strFieldsArr(0) ' Save the Date...
    cTransArr(1, sNdx) = strFieldsArr(1)
    cTransArr(2, sNdx) = strFieldsArr(2) ' Save the Amount...
    strLine = objStreamReader.ReadLine() ' Read the next line from file...
    sNdx += 1 ' Increment the subscript.

    End While

    Try


    Dim strListLine As String
    Dim result As Double
    lstbox.Items.Clear() ' Clear the ListBox contents
    For sNdx = 0 To cTransArr.GetUpperBound(1) ' Go through the array elements..
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    If cTransArr(2, sNdx) <> 0 Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then


    strListLine = String.Format("{0,-11}", cTransArr(0, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(1, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(2, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", result)
    lstbox.Items.Add(strListLine) ' Add the formatted transaction to the listBox
    End If
    End If

    Next
    For sNdx = 0 To cTransArr.GetUpperBound(1)
    If cTransArr(2, sNdx) = 0 Then
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    Next
    Catch ex As InvalidCastException
    MessageBox.Show("Data Type Error..." & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Press OK to Continue", "Data Type Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try





    End Sub[/code]
  • seancampbellseancampbell Pennsylvania, USA
    Ok, this is done with a very simple "concept" called Data Validation. When you are recieving input from somewhere, like a file, or user entry, it is best to "Validate" the data unless you know 100% for sure that the data will be in a good format (ex. I just retrieved 100 database records in a csv file, I know that all data will be good).

    So, to validate the data that is received from your source, you will want to use If Statement logic.

    If the line doesnt have enough spaces, or, if the split array isn't long enough

    If a certain value equals zero

    If any of the numbers are not infact numbers

    These cases are easy to check for progromatically. There is several ways to check these, and based on the logic calculate or not calculate, but in your example, because you are a novice programmer, a nested If statement will probably work best.
    [code]
    If strFieldsArr.Length >= 3 Then

    Else
    'Not enough data to fillout cTransarr
    End If
    [/code]
    [code]
    If isNumeric(cTransArr(0, sNdx)) = True Then
    If isNumeric(cTransArr(1, sNdx)) = True Then
    If isNumeric(cTransArr(2, sNdx)) = True Then
    If cTransArr(2, sNdx) <> 0 Then

    Else
    'If cTransArr(2, sNdx) = 0 then there will be a div by 0 error
    End If
    End If
    End If
    End If
    [/code]

    The top one should be used when capturing your data from the file
    [code]
    cTransArr(0, sNdx) = strFieldsArr(0) ' Save the Date...
    cTransArr(1, sNdx) = strFieldsArr(1)
    cTransArr(2, sNdx) = strFieldsArr(2) ' Save the Amount...
    sNdx += 1

    'This should always happen and shouldn't be in an if statement
    strLine = objStreamReader.ReadLine() ' Read the next line from file...
    [/code]

    The bottom one for making sure the numbers you are calculating will not return a Div By 0 error.
  • You still don't get my problem.. as soon as it is reading in the file Joe it is giving me an error.. then stops making the calculations..
    I need to be able to continue my calculations....
    here is what my code looks like now :
    [code] Try


    Dim strListLine As String
    Dim result As Double
    lstbox.Items.Clear() ' Clear the ListBox contents
    For sNdx = 0 To cTransArr.GetUpperBound(1) ' Go through the array elements..
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    If IsNumeric(cTransArr(0, sNdx)) = True Then
    If IsNumeric(cTransArr(1, sNdx)) = True Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then
    If cTransArr(2, sNdx) <> 0 Then



    strListLine = String.Format("{0,-11}", cTransArr(0, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(1, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(2, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", result)
    lstbox.Items.Add(strListLine) ' Add the formatted transaction to the listBox
    ElseIf IsNumeric(cTransArr(2, sNdx)) = False Then
    MessageBox.Show("Invalid Numerical Value..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    End If
    End If
    End If
    Next
    Catch ex As InvalidCastException
    MessageBox.Show("Data Type Error..." & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Press OK to Continue", "Data Type Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)

    End Try[/code]
  • seancampbellseancampbell Pennsylvania, USA
    You are right. I must not "get" your problem. Why don't you start by giving me the exact error message that you are getting. Copy the details from the exception and paste them in here.
  • seancampbellseancampbell Pennsylvania, USA
    haha, maybe I was right, and your code was wrong? Try this revised code, I commented what I changed:

    [code]

    Try
    Dim strListLine As String
    Dim result As Double
    lstbox.Items.Clear() ' Clear the ListBox contents
    For sNdx = 0 To cTransArr.GetUpperBound(1) ' Go through the array elements..
    'reset Result for last part if data was bad
    result = 0

    'We cannot calculate a formula without validating the data...
    'Whats the point of validating data if you are going to use it first?
    If IsNumeric(cTransArr(0, sNdx)) = True Then
    If IsNumeric(cTransArr(1, sNdx)) = True Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then
    If cTransArr(2, sNdx) <> 0 Then
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    ElseIf IsNumeric(cTransArr(2, sNdx)) = False Then
    MessageBox.Show("Invalid Numerical Value..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    End If
    End If
    End If
    'This is all string manipulation, as long as cTransArr's bounds are good, we should be able to use these
    strListLine = String.Format("{0,-11}", cTransArr(0, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(1, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(2, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", result)
    lstbox.Items.Add(strListLine) ' Add the formatted transaction to the listBox
    Next
    Catch ex As InvalidCastException
    MessageBox.Show("Data Type Error..." & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Press OK to Continue", "Data Type Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)

    End Try

    [/code]
  • Ok well what you did fixed things up.. but nevertheless.. it isn't getting the invalid numerical value error.. in my file there is a name instead of a number.. and it's not sending me an error about it.. thx other than that everything is working :)
    [code] Try
    Dim strListLine As String
    Dim result As Double
    lstbox.Items.Clear() ' Clear the ListBox contents
    For sNdx = 0 To cTransArr.GetUpperBound(1) ' Go through the array elements..
    'reset Result for last part if data was bad
    result = 0

    'We cannot calculate a formula without validating the data...
    'Whats the point of validating data if you are going to use it first?
    If IsNumeric(cTransArr(0, sNdx)) = True Then
    If IsNumeric(cTransArr(1, sNdx)) = True Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then
    If cTransArr(2, sNdx) <> 0 Then
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    ElseIf IsNumeric(cTransArr(2, sNdx)) = False Then
    MessageBox.Show("Invalid Numerical Value..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    End If
    End If
    End If
    If result > 50000 Then
    'This is all string manipulation, as long as cTransArr's bounds are good, we should be able to use these
    strListLine = String.Format("{0,-11}", cTransArr(0, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(1, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", cTransArr(2, sNdx))
    strListLine = strListLine & String.Format("{0,-11}", result)
    lstbox.Items.Add(strListLine) ' Add the formatted transaction to the listBox
    End If
    Next
    Catch ex As InvalidCastException
    MessageBox.Show("Data Type Error..." & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Press OK to Continue", "Data Type Error...", MessageBoxButtons.OK, MessageBoxIcon.Error)

    End Try[/code]
  • seancampbellseancampbell Pennsylvania, USA
    It is most likely becuase you check that cTransArr is numeric before you check if it <> 0... If it is not a number, it simply skips it (there is no else case to this one)

    [code]
    If IsNumeric(cTransArr(0, sNdx)) = True Then
    If IsNumeric(cTransArr(1, sNdx)) = True Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then
    'If we get here, all values in cTransArr( ,sNdx) are numeric
    If cTransArr(2, sNdx) <> 0 Then
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    ElseIf IsNumeric(cTransArr(2, sNdx)) = False Then
    'This case will never happen, because of your check above,
    MessageBox.Show("Invalid Numerical Value..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    End If
    End If
    End If
    [/code]
    maybe this will work for you
    [code]
    If IsNumeric(cTransArr(0, sNdx)) = True Then
    If IsNumeric(cTransArr(1, sNdx)) = True Then
    If IsNumeric(cTransArr(2, sNdx)) = True Then
    'If we get here, all values in cTransArr( ,sNdx) are numeric
    If cTransArr(2, sNdx) <> 0 Then
    result = ((cTransArr(0, sNdx) * 2000) / 32) * (((cTransArr(1, sNdx) * 1.466) * (cTransArr(1, sNdx) * 1.466)) / cTransArr(2, sNdx))
    Else
    MessageBox.Show("Devide by Zero Not Allowed..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    Else
    'This case happens when IsNumeric(cTransArr(2, sNdx)) = False
    MessageBox.Show("Invalid Numerical Value..." & vbNewLine & vbNewLine & "Press OK to Continue", "Exception Ocurred...", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If
    End If
    End If
    [/code]

    The code holds all of the answers, if you are not getting the results you expect, it is usually because your syntax or the order you execute your code in is messed up.

    In this case, you have put code into your program that you might not fully understand, so when things happen differently then you thought, it makes you scratch your head. Typically, when things happen that I do not understand, I step through the code one line at a time. This is an awesome debugging technique, because you can view the state of all of your variables and catch exactly what is happenning when your code is executing.

    Because explaining stepping through code is a bit lengthy (and I am at work so I shouldn't even be on here) here is a really sweet article I give to students I tutor, it should help you learn to debug your code 1 line at a time: http://www.homeandlearn.co.uk/net/nets5p6.html

    Hope I helped,
    Sean Campbell, programmer/musician/22yo punk kid
    firesickle.com
  • So just scanning over this -

    If you are indeed having trouble reading your own code it may be because it is actually very difficult to read.

    Wouldn't this be way easier to deal with?
    [code]
    Module Module1

    Sub Main()
    Dim items = FileItem.FromFile("C:SomeFile.txt", AddressOf MyErrorHandler)

    Dim anExampleItem = items(0) ' or 1 or 2 or 3...

    Dim theWeight = anExampleItem.Weight
    Dim theSpeed = anExampleItem.Speed
    Dim theRadius = anExampleItem.Radius

    Try
    Dim theForce = anExampleItem.GetForce()
    Catch ex As DivideByZeroException
    Console.WriteLine("Couldn't get the force because of a divide by 0 error")
    End Try
    End Sub

    Public Sub MyErrorHandler(ByVal ex As Exception)
    Console.WriteLine(ex.Message)
    End Sub

    End Module
    [/code]

    FileItem.FromFile does all the parsing and file reading for you and creates a bunch of "FileItem" objects that you can work with as objects

    Dim item as FileItem

    is as easy to work with as

    item.Weight
    item.Speed
    or
    item.GetForce()

    the static FromFile method gives you a collection of FileItems - way easier to work with and then read later on.

    All you have to do is pop your functionality into a class

    [code]
    Public Class FileItem

    ' Comming from a C++/C# background it seems like a whole lot of extra work to create properties
    ' in VB.NET - Wont it be nice when "Auto Properties" are introduced into VB?
    Public Time As DateTime
    Public Weight As Double
    Public Speed As Double
    Public Radius As Double

    ' This function will provide force based on the existing data
    Public Function GetForce() As Double
    Try
    Return ((Weight * 2000) / 32) * (((Speed * 1.466) * (Speed * 1.466)) / Radius)
    Catch ex As DivideByZeroException
    Throw (New DivideByZeroException("Force can not be calculated if radius=0"))
    End Try
    End Function

    ' Sorry - I wasn't able to gather how exactly your file was formatted according to your original post:
    Public Sub New(ByVal raw As String)
    Dim strings = raw.Split(" ") ' Do the parsing in the class constructor
    If ((Not DateTime.TryParse(strings(0), Time)) _
    And (Not Double.TryParse(strings(1), Weight)) _
    And (Not Double.TryParse(strings(2), Speed)) _
    And (Not Double.TryParse(strings(3), Radius))) Then
    Throw (New BadEntryException("Could not parse " & raw)) ' Throw a custom error if something can't be parsed
    End If
    End Sub

    ' You can actually add a static method onto this class that knows how to read itself out of a file...
    Public Shared Function FromFile(ByVal path As String, ByVal onError As Action(Of Exception)) As List(Of FileItem)
    Dim contents = System.IO.File.ReadAllText(path)
    Dim reader = New System.IO.StringReader(contents)
    Dim results = New List(Of FileItem)
    Dim line = reader.ReadLine()
    While (Not line Is Nothing)
    Try
    results.Add(New FileItem(line))
    Catch ex As Exception
    onError(ex) ' Send the error handling back to the caller
    Finally
    line = reader.ReadLine()
    End Try
    End While
    Return results
    End Function

    ' Override the ToString function and make each record display however you want it...
    Public Overrides Function ToString() As String
    Dim result = "Record: "
    result += "Weight=" & Weight & ", "
    result += "Speed=" & Speed & ", "
    result += "Radius=" & Radius & ", "
    result += "Force=" & GetForce()
    Return result
    End Function

    ' Our own personal exception type
    Public Class BadEntryException
    Inherits Exception

    Public Sub New(ByVal message As String)
    MyBase.New(message)
    End Sub
    End Class
    End Class
    [/code]

    I mean I know it can look scary if you are not familiar with object oriented programming, but once you get used to it - its really like a breath of fresh air - and it is sooo much easier to maintain your code later.

    Just some extra thoughts :)


    ><//~Psightoplasm`~
  • seancampbellseancampbell Pennsylvania, USA
    I like your point Psightoplasm, definitely would be proper to do it your way, but I think Baller is a novice coder, still in school

    Looking at your code would be quite confusing if I didn't know Classes (OOP), Execption Handling, Making my own Functions, what a property is...

    I tend to work around the code people post in here, because they might not see my way as a better way (I know I am stubborn in this way), and I don't like writing code for someone that they won't understand entirely

    Thanks for the followup,
    sean c
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories