Link to home
Start Free TrialLog in
Avatar of nflowers1228
nflowers1228

asked on

Splitting Text File Data for Use in Array

I am taking a class and am a real newbie. I am working on a mortgage calculator. I need to allow the user to select the mortgage terms and interest rates (i.e. 7 years @ 5.5%) from a ListBox,  grab the values from an array in a text file based on that selection and then calculate the mortgage payment with the term and the rate read as separate properties/variables.

So the first task is to get the values from the text file which reads:
7, 5.35
15, 5.5
30, 5.75

When I run the code below, I just get the values for the first and second "fields" in the first record. How do I move on to the next line?

  Private Sub uiArrayValueButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiArrayValueButton.Click
        'displays the interest rates from the text file
        Dim loanArrayStreamReader As IO.StreamReader
        Dim record As String
        Dim indexNum
        Dim mortgageTerm As String
        Dim mortgageTermArray As Integer
        Dim array As String
        Dim ListBoxIndex As String

        Me.uiDisplayLoanTypeLabel.Text = ""

        'determine if text file exists
        If IO.File.Exists("loans.txt") Then
            'create a stream reader object by opening the file for input
            loanArrayStreamReader = IO.File.OpenText("loans.txt")

            'process the loop
            Do Until loanArrayStreamReader.Peek() = -1
                'read the record from the file
                record = loanArrayStreamReader.ReadLine()
                'record = loanArrayStreamReader.ReadToEnd() 'suggestion of the instructor which moves to the next line, but only gives me the first three "fields" of the text file
                'display the term of the record
                indexNum = record.IndexOf(",")
                'mortgageTerm = record.Substring(0, indexNum) displays the mortgage term
                mortgageTerm = record.Substring(indexNum + 1) 'displays the mortgage rate

                Me.uiDisplayLoanTypeLabel.Text = Me.uiDisplayLoanTypeLabel.Text & mortgageTerm & vbNewLine
            Loop
        End If
 
    End Sub

The instructor passed on this code which helps me getting the "fields" from the first record, splitting the line at the comma, but again, I'm not sure how to get to the second line. She assumed that the rates were on one line and the terms on another.

    Private Sub uiDisplayButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiDisplayButton3.Click
        'genevieve's example
        Dim loans As String ' file name
        Dim loanArrayStreamReader As IO.StreamReader ' stream reader to read the file
        Dim splitCharacter As String = ","
        Dim strRates As String ' assuming this is for the interest rates.
        loans = "C:\Save This Stuff\school\VBAdvanced\Individual Assignments\NancyFlowers-MangsMortgageCalculator- ProjectThreeV1\NancyFlowers-MangsMortgageCalculator\bin\loans.txt"
        loanArrayStreamReader = New IO.StreamReader(loans)
        strRates = loanArrayStreamReader.ReadLine() 'reads the first line of the file
        'strRates = loanArrayStreamReader.ReadToEnd() 'reads the first line of the file
        Dim sarrRates() As String = strRates.Split(splitCharacter)

        For i As Integer = 0 To UBound(sarrRates)
            'MessageBox.Show(sarrRates(i))
            Me.uiArrayType1PaymentLabel.Text = sarrRates(0) & " " & sarrRates(1)
            'Me.uiArrayType1PaymentLabel.Text = sarrRates(1)
        Next

     End Sub

any help would be appreciated... I'm sure I'll be just as challenged by trying to assign the value to the index number of the List Box, but if I could get this figured out, it would be a big help.

nancy
SOLUTION
Avatar of lojk
lojk
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nflowers1228
nflowers1228

ASKER

Yes this helps, especially in the understanding of working with OO programming. This is a difficult hurdle to overcome. One problem I did have was in the reference to tVars. I got an error when it got to that point in the ListBox1 Sub. Not sure how to fix that... or get past it :-)

Thanks again for your help.  
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your help. I did find the error and the problem was that I was clicking on the index option item, then clicking on the button. If I just clicked on the button the items displayed 

I did take your advice and chunk up the code on the page. Here is a problem that I’m having general that is somewhat related. I can’t seem to get past this…

Declared the common variables at the top of the page:

    Dim MortgageTerm As Double
    Dim MortgageAmount As Double
    Dim InterestRate As Double
    Dim Payment As Double

Created a Calculate Payment function which takes the values from the text fields on the form:

  Public Function CalculatePayment()
'calcualtes based on the value entered in the Mortgage Term Field
        MortgageAmount = Val(Me.uiMortgageAmountTextBox.Text)
        MortgageTerm = Val(Me.uiMortgageTermTextBox.Text) * 12
        InterestRate = Val((Me.uiInterestRateTextBox.Text) / 100) / 12

        Return (-Financial.Pmt((InterestRate), MortgageTerm, MortgageAmount))

    End Function

Click on a button and the stuff calculates 
    Private Sub uiCalculatePaymentButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiCalculatePaymentButton.Click

        'clicking this button calculates the mortgage payment
        Dim Payment As Double = CalculatePayment()

        Me.uiDisplayPaymentLabel.Text = Format(Payment, "currency")
       
    End Sub

--That works fine : -)

But when I try to use the variables again, even to just display them in a text box or label, they won’t display. No matter what I do it turns up as the value is 0. (sorry this is not your code, because I couldn’t get it to work, I tried another avenue)
--
Public Function CaculatePaymentTextFile()
        Dim MortgageTerm As Double
        Dim MortgageAmount As Double
        Dim Payment As Double
        Dim InterestRate As String

        Dim loans As String ' file name
        Dim loanArrayStreamReader As IO.StreamReader ' stream reader to read the file
        Dim splitCharacter As String = ","
        Dim strRates As String '  interest rates.
        Dim strTerms As String '  mortgage term.
        loans = "C:\Save This Stuff\school\VBAdvanced\Individual Assignments\NancyFlowers-MangsMortgageCalculator- ProjectThreeV1\NancyFlowers-MangsMortgageCalculator\bin\loans.txt"
        loanArrayStreamReader = New IO.StreamReader(loans)

        'declare the values of the mortgage terms and interest rate variables
        strRates = loanArrayStreamReader.ReadLine() 'reads the interest rates
       
 'single dimensional array
        strTerms = loanArrayStreamReader.ReadLine() 'reads the mortgage terms
        Dim sarrRates() As String = strRates.Split(splitCharacter)
        Dim sarrTerms() As String = strTerms.Split(splitCharacter)


        If Me.uiLoanTypeListBox.SelectedIndex = 0 Then
            'this just shows me that pulling the values is working :-)
            MortgageTerm = sarrTerms(0)
            InterestRate = sarrRates(0)
        ElseIf Me.uiLoanTypeListBox.SelectedIndex = 1 Then
            InterestRate = sarrRates(1)
            MortgageTerm = sarrTerms(1)

        ElseIf Me.uiLoanTypeListBox.SelectedIndex = 2 Then
            InterestRate = sarrRates(2)
            MortgageTerm = sarrTerms(2)
        End If

        Return (-Financial.Pmt((InterestRate), MortgageTerm, MortgageAmount))
    End Function

I tried a simpler version to see if I could extract just the Mortgage term and I can’t even do that, it shows up a zero.

Public Function CheckValues()

        ‘this is commented out because I tried to call the values from the text boxes again and clearly that doesn’t work.
       'MortgageAmount = Val(Me.uiMortgageAmountTextBox.Text)
        'MortgageTerm = Val(Me.uiMortgageTermTextBox.Text) * 12
       'InterestRate = Val((Me.uiInterestRateTextBox.Text) / 100) / 12

 Dim NumberPayments = MortgageTerm * 12 ‘hoping this would pull MortgageTerm from the values entered before

        Return NumberPayments & "help")
    End Function

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Me.TextBox2.Text = CheckValues()
End Sub

I get 0help when I generate this… If this is too lengthy to handle I totally understand. I just want to know how to reuse the variables. I’m probably way off base. Please let me know if I’m hopeless…

THANKS!
I got it to work. thanks for your help. I know I didn't use your code directly, but your logic was really helpful. I was better able to understand where i needed to go. I know it's not perfect, but it works :-) Thanks for all your help and encouragement... looking forward to more programming.

Public Class MortgageCalculatorForm
    Dim MortgageTerm As Double
    Dim MortgageAmount As Double
    Dim Payment As Double
    Dim InterestRate As Double

Private Sub MortgageCalculatorForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'declares INITIAL Amounts for data entry fields on the screen
        Me.uiMortgageAmountTextBox.Text = ""
        Me.uiDisplayPaymentLabel.Text = ""
        Me.uiAmortTableRichTextBox.Text = ""
        Me.uiMortgageAmountTextBox.Focus()
        Me.uiLoanTypeListBox.SelectedIndex = 0

    End Sub


Private Sub uiCalculatePaymentButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uiCalculatePaymentButton.Click

        'clicking this button calculates the mortgage payment

        'Dim Payment As Double


        If Me.uiMortgageTermTextBox.Text <> "" AndAlso Me.uiInterestRateTextBox.Text <> "" Then
            Payment = CalculatePayment()
        Else
            Payment = CaculatePaymentTextFile()
        End If

        Me.uiDisplayPaymentLabel.Text = Format(Payment, "currency")
        Me.uiAmortTableRichTextBox2.Text = amortTable()

    End Sub

Private Sub uiAmortTableRichTextBox_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles uiAmortTableRichTextBox.KeyPress
        'based on Douglass Cole's suggestion and code snippet. Thanks Douglass :-)
        'Suppress the keypress in textbox without disabling the textbox
        e.Handled = True
    End Sub

Private Sub uiAmortTableRichTextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles uiAmortTableRichTextBox2.KeyPress
        'based on Douglass Cole's suggestion and code snippet. Thanks Douglass :-)
        'Suppress the keypress in textbox without disabling the textbox
        e.Handled = True
    End Sub
    Public Function CalculatePayment()
        Dim MortgageTerm As Double
        Dim MortgageAmount As Double
        'Dim Payment As Double
        Dim InterestRate As Double

        MortgageAmount = Val(Me.uiMortgageAmountTextBox.Text)
        MortgageTerm = Val(Me.uiMortgageTermTextBox.Text) * 12 'calcualtes the mortgage term based on the value entered in the Mortgage Term Field
        InterestRate = Val(Me.uiInterestRateTextBox.Text / 100) / 12

        Return (MortgageAmount * (InterestRate) / (1 - Math.Pow(1 + (InterestRate), -(MortgageTerm))))
       
End Function
Private Function CaculatePaymentTextFile()

        Dim loans As String ' file name
        Dim loanArrayStreamReader As IO.StreamReader ' stream reader to read the file
        Dim splitCharacter As String = ","
        Dim strRates As String '  interest rates.
        Dim strTerms As String '  mortgage term.

        MortgageAmount = Val(Me.uiMortgageAmountTextBox.Text)
        loans = "C:\loans.txt"
        loanArrayStreamReader = New IO.StreamReader(loans)

        'declare the values of the mortgage terms and interest rate variables
        strRates = loanArrayStreamReader.ReadLine() 'reads the interest rates
        'single dimensional array
        strTerms = loanArrayStreamReader.ReadLine() 'reads the mortgage terms
        Dim sarrRates() As String = strRates.Split(splitCharacter)
        Dim sarrTerms() As String = strTerms.Split(splitCharacter)


        If Me.uiLoanTypeListBox.SelectedIndex = 0 Then
            'this just shows me that pulling the values is working :-)
            MortgageTerm = sarrTerms(0)
            InterestRate = sarrRates(0)
        ElseIf Me.uiLoanTypeListBox.SelectedIndex = 1 Then
            InterestRate = sarrRates(1)
            MortgageTerm = sarrTerms(1)

        ElseIf Me.uiLoanTypeListBox.SelectedIndex = 2 Then
            InterestRate = sarrRates(2)
            MortgageTerm = sarrTerms(2)
        End If

Return (MortgageAmount * (InterestRate / 100) / 12) / (1 - Math.Pow(1 + (InterestRate / 100) / 12, -(MortgageTerm * 12)))

End Function
End Class
Hi , Only just got round to checking on this...

I notice in your version that works you have commented the

Dim Payment as Double Line

This is the killer and is what is known as Variable Scoping; it is the scope at which the variable is defined....

Because at the top you have Dimmed Payment once, that variable is accesible to every method(sub/function) within that Class(form) but because VB.Net is what is known as 'Strongly Typed' there is nothing to stop you from defining a Variable within a Method even of the same name (in the good old days VB6 would complain, vigourously about this).

As far as .Net is concerned  because you have defined it *within* that method (ie the 'scope' of the variable is Local not Global to that method) whenever, within that method you refer to Payment it thinks you mean the Payment variable within that method. If within that method you did want *another* variable of the same name as the global defined one to set the Form-Scope variable value instead you have to tell it where it is by using

Me.Payment = 2323
otherwise just
Payment=2323
sets the Payment variable that you have explicity created with the CreatePayment Function

Funnily enough the best way to do things is not always with wide scope varaibles anyway, it is usually better to go down the OO route, heres an example

Public Class MortgageCalculator
 
    Public MortgageTerm As Double
    Public MortgageAmount As Double
    Public InterestRate As Double

    Public Overloads Function CalculatePayment()
        Return (MortgageAmount * (InterestRate) / (1 - Math.Pow(1 + (InterestRate), -(MortgageTerm))))
    End Function


    Public Overloads Function CalculatePayment(ByVal nMortgageAmount As Double, ByVal nMortgageTerm As Double, ByVal nPayment As Double, ByVal nInterestRate As Double) As Double

        MortgageAmount = Val(nMortgageAmount)
        MortgageTerm = Val(nMortgageTerm)  
        InterestRate = Val(nInterestRate)
        Return CalculatePayment


    End Function

End Class

Now very roughly ( i havenet got the right formulas and numbers here ,i know) at the top of your Form you can

Dim myMortgageCalculator as new MortgageCalculator

And then when you want to calculate a result all you have to do is either

myMortgageCalculator.MortgageTerm=23
myMortgageCalculator.Interestrate=21
myMortgageCalculator.MortgageAmount=2323
ResultTextBox.Text = myMortgageCalculator.CalculatePayment

or (and the or is because the Same Function has two different Parameter Sets) even better
ResultTextBox.Text = myMortgageCalculator.CalculatePayment(23,21,2323)

This is *the* way to do it, it also helps to group the Variables and realted functions together and out of the way of the Form Code and improves readability and reusability. Obviously within that Mortgage Calculator Class you couls/should move the logic for reading the File in too, so all that your form needs to know how to do is query a MortgageCalculator Object...

It maybe worth a couple of hours of your time in the MSDN and read a little about Variable Scoping,Overloading. Namespaces and Instantiating Objects. In fact i spend much of my time in the MSDN - its just not possible for a human to know everything that there is to know about .NET

'F1' is your friend!!!

Thanks for the points BTW :-) You are my officially my first 'EE Customer', glad to be of help... and i hope this comment hasnt furhter confused you..
Thanks. This was really helpful. I'm still working on the classes (I posted an entirely different thread for that one :-) I was able to get the classes working for the first iteration of this project, but when I started combining the two, I had a lot of trouble. I know it will just take time and practice....