locked
Problem using loops for dynamic list RRS feed

  • Question

  • Hey Guys, I'm new with VB 2012 and I'm trying to write code to make a Lagrange Interpolation. While doing this task, I tried to use list and a loop to store data in it for a given number like n. But it is now working and it keeps popping out this error: "Conversion from string "" to type 'Double' is not valid." as I'm trying to insert number in textbox2.text. ( I tried to use Cdl or CInt but they didn't work either). I would appreciate any help. These are the codes I have written:

    Public Class Form1
         Public myarray As New List(Of Double)
         Public myarray2 As New List(Of Double)
         Dim n As Integer
         Public x As Double
    
             Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
             Button1.Enabled = False
             Button2.Enabled = True
    
         End Sub
         Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
             x = TextBox3.Text
             n = TextBox1.Text
             Dim k As Integer
    
            Do While k < n
                 myarray.Add(TextBox2.Text)
                 TextBox2.Clear()
                 k += 1
                 Button1.Enabled = False
                 Button2.Enabled = True
    
             Loop
             Do While k < n
    
                 myarray2.Add(TextBox5.Text)
                 TextBox5.Clear()
    
             Loop
             Button1.Enabled = True
    
             Button2.Enabled = False
    
         End Sub
         
        
    
         Private Function total() As Double
    
    
             Dim i, j As Integer
             Dim mlt As Double
             Dim sum As Double
    
            For i = 0 To myarray.Count - 1
    
                 mlt = 1
    
                 For j = 0 To myarray.Count - 1
    
                     If j <> i Then
                         mlt = mlt * ((x - myarray.Item(j)) / (myarray.Item(i) - myarray.Item(j)))
    
                     End If
    
                 Next
                 'sum += mlt
                 sum += mlt * myarray2.Item(i)
    
             Next
             Return sum
    
         End Function
    
         Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
             ListBox1.Items.Add("x_i" & vbTab & "y_i")
             ListBox1.Items.Add("——————————")
    
             Dim num As Integer
    
             For num = 0 To myarray.Count - 1
                 ListBox1.Items.Add(myarray.Item(num) & vbTab & myarray2.Item(num))
    
             Next
             
             TextBox4.Text = total()
             Button1.Enabled = True
             Button2.Enabled = False
    
         End Sub
         
     End Class


     
    • Edited by Reed KimbleMVP Wednesday, July 1, 2015 4:30 AM placed coded in code block
    Wednesday, July 1, 2015 1:56 AM

Answers

  • The error message is telling you that you are trying to convert an empty string ("") to a Double. You didn't say which statement is getting the error, but the following loops will get that error at least on the second time through the loop.

    Do While k < n
        myarray.Add(TextBox2.Text)
        TextBox2.Clear()
        k += 1
        Button1.Enabled = False
        Button2.Enabled = True
    Loop
    

    The first time through the loop you clear TextBox2 and the second time through the loop you try to convert the empty string in the TextBox to a Double (so you can add it to myarray. I'm not sure what that code is supposed to do, but you at least need to address that problem.

    You should also consider that the next loop

    Do While k < n
        myarray2.Add(TextBox5.Text)
        TextBox5.Clear()
    Loop

    will never execute since the first loop doesn't finish until k is equal to n.

    I recommend that you add the statement

    Option Strict On

    as the very first statement in your code file. That will flag statement like 

    myarray.Add(TextBox2.Text)

    as errors as the conversion from String (TextBox2.Text) to Double (an item in myarray) will not always work.

    • Proposed as answer by Reed KimbleMVP Wednesday, July 1, 2015 4:31 AM
    • Marked as answer by Youjun Tang Thursday, August 13, 2015 6:11 AM
    Wednesday, July 1, 2015 2:45 AM
  • It is hard to tell what you expect this code to do. I think what you want is the following. Note that I don't know how to calculate a LaGrange Interpolation, so I wasn't able to verify the calculation. Also note that I tried to give the variables and controls more meaningful names.

    Public Class Form1
        Private myList1 As New List(Of Double)
        Private myList2 As New List(Of Double)
    
        Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
            Dim num1, num2 As Double
            If Not Double.TryParse(Item1Box.Text, num1) Then
                MessageBox.Show("Enter a valid number for the first list")
                Exit Sub
            End If
            If Not Double.TryParse(Item1Box.Text, num2) Then
                MessageBox.Show("Enter a valid number for the second list")
                Exit Sub
            End If
            myList1.Add(num1)
            myList2.Add(num2)
        End Sub
    
        Private Sub CalcButton_Click(sender As Object, e As EventArgs) Handles CalcButton.Click
            Dim x As Double
            If Not Double.TryParse(XBox.Text, x) Then
                MessageBox.Show("Enter a valid number for X")
                Exit Sub
            End If
    
            ListBox1.Items.Add("x_i" & vbTab & "y_i")
            ListBox1.Items.Add("——————————")
            For num As Integer = 0 To myList1.Count - 1
                ListBox1.Items.Add(myList1(num).ToString & vbTab & myList2(num).ToString)
            Next
    
            TotalBox.Text = CalcTotal(x).ToString
        End Sub
    
        Function CalcTotal(x As Double) As Double
            Dim sum As Double
    
            For i As Integer = 0 To myList2.Count - 1
                Dim mlt As Double = 1
                For j As Integer = 0 To myList1.Count - 1
                    If j <> i Then mlt *= (x - myList1.Item(j)) / (myList1.Item(i) - myList1.Item(j))
                Next
                sum += mlt * myList2.Item(i)
            Next
    
            Return sum
        End Function
    
    End Class

    • Marked as answer by Abed_1234 Wednesday, July 1, 2015 5:19 PM
    Wednesday, July 1, 2015 5:08 PM

All replies

  • The error message is telling you that you are trying to convert an empty string ("") to a Double. You didn't say which statement is getting the error, but the following loops will get that error at least on the second time through the loop.

    Do While k < n
        myarray.Add(TextBox2.Text)
        TextBox2.Clear()
        k += 1
        Button1.Enabled = False
        Button2.Enabled = True
    Loop
    

    The first time through the loop you clear TextBox2 and the second time through the loop you try to convert the empty string in the TextBox to a Double (so you can add it to myarray. I'm not sure what that code is supposed to do, but you at least need to address that problem.

    You should also consider that the next loop

    Do While k < n
        myarray2.Add(TextBox5.Text)
        TextBox5.Clear()
    Loop

    will never execute since the first loop doesn't finish until k is equal to n.

    I recommend that you add the statement

    Option Strict On

    as the very first statement in your code file. That will flag statement like 

    myarray.Add(TextBox2.Text)

    as errors as the conversion from String (TextBox2.Text) to Double (an item in myarray) will not always work.

    • Proposed as answer by Reed KimbleMVP Wednesday, July 1, 2015 4:31 AM
    • Marked as answer by Youjun Tang Thursday, August 13, 2015 6:11 AM
    Wednesday, July 1, 2015 2:45 AM
  • While doing this task, I tried to use list and a loop to store data in it for a given number like n.

    Your code to get the values from the user is not structured correctly.  It should be something like:

        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
             Static k As Integer
             n = TextBox1.Text
    If k < n myarray.Add(TextBox2.Text) TextBox2.Clear() myarray2.Add(TextBox5.Text) TextBox5.Clear() k += 1 Else MsgBox("Too Many Entries") End If End Sub
    (before adjusting for the problem of the conversions, which is the error you currently have).  The user will click the button after entering each pair of data items in the text boxes.  IF you correctly test for invalid input, then by clearing the text boxes you are ensuring that the user is forced to enter new values each time.
    Wednesday, July 1, 2015 3:15 AM
  • You should be converting types before using them normally.

    Type Conversions in Visual Basic

    Type Conversion Functions (Visual Basic)

    TextBox text is a string. A string can contain pretty much anything. There's various capabilities to test a string to see if it IsNumeric or use one of the TryParse methods to attempt to parse a string to some type of numeric type like Double.TryParse.

    Also you can test a textbox's text to see if it even contains anything prior to trying to check it.

    If TextBox1.Text <> "" Then

    ' do stuff here

    End If


    La vida loca

    Wednesday, July 1, 2015 3:46 AM
  • In the that part I'm attempting to unable button1 to force the user first insert the adequate data into my lists. Without this task, it was working properly. I thought that by using one (or two) loops it can be done. I tried this one too, it didn't work though.

    Do While k < n
                 myarray.Add(TextBox2.Text)
                 TextBox2.Clear()
                 myarray2.Add(TextBox5.Text)
                 TextBox5.Clear()
    
             Loop

     Actually I'm surprised that if it is not correct why is it working as I'm not using loops but not after that? It gives the mentioned error which seams not reasonable. I will examine the "Static Option" and let you know if it is working fittingly. 


    Abed_4321

    Wednesday, July 1, 2015 3:17 PM
  • In the that part I'm attempting to unable button1 to force the user first insert the adequate data into my lists. Without this task, it was working properly. I thought that by using one (or two) loops it can be done. I tried this one too, it didn't work though.

    Do While k < n
                 myarray.Add(TextBox2.Text)
                 TextBox2.Clear()
                 myarray2.Add(TextBox5.Text)
                 TextBox5.Clear()
    
             Loop

     Actually I'm surprised that if it is not correct why is it working as I'm not using loops but not after that? It gives the mentioned error which seams not reasonable. I will examine the "Static Option" and let you know if it is working fittingly. 


    Abed_4321

    Think about what happens in that loop.

    The first time round, you convert the text in TextBox2 to a Double and add the double to myarray (this will cause an error if the text in TextBox2 can't be converted to a Double. Then you clear TextBox2. Next you do the same with TextBox5 and myarray2.

    The second time round the loop, you again convert the text in TextBox2 to a Double and add the double to myarray. This will always cause an error because you cleared the TextBox the first time round the loop.

    Perhaps what you want to do is have the user enter something in the TextBoxes and then click the Button to have you process them. The user can do this several times until you have as many items in myarray and myarray2 as you want.

    If you add the statement

    Option Strict On

    as the first statement in your file. This will flag several questionable conversions as errors. In all the cases where the user has entered something in a TextBox and you want to convert that into an Integer or a Double, you should validate the input first. You can use Integer.TryParse and Double.TryParse to do that.

    Wednesday, July 1, 2015 3:34 PM
  • I did what you said and then it gives me this error:

    Error 1: Overload resolution failed because no accessible 'TryParse' accepts this number of arguments.

    Once again, without using the loop it's working functionally. As I want to unable button1 before getting enough entries, I'm using the loops ( I tried one loop too).



    Abed_4321

    Wednesday, July 1, 2015 4:05 PM
  • I did what you said and then it gives me this error:

    Error 1: Overload resolution failed because no accessible 'TryParse' accepts this number of arguments.

    Once again, without using the loop it's working functionally. As I want to unable button1 before getting enough entries, I'm using the loops ( I tried one loop too).



    Abed_4321

    The error message is saying that you didn't code the TryParse call correctly. Either read the documentation I linked to to find the correct way of calling it, or post the code that you are using to call it.
    Wednesday, July 1, 2015 4:08 PM
  • I tried static and it solved the error problem but now it does not get out of that "if" and keeps unable the button1. When you enter more than variable "n", it says : "Too many Entries".

    Abed_4321

    Wednesday, July 1, 2015 4:13 PM
  • For example, this is one of them:

    "n = Double.TryParse(TextBox1.Text)".

    I don't know if I have done it correctly (I'm not familiar with "option strict on" method), just following what you mentioned.

            

    Abed_4321

    Wednesday, July 1, 2015 4:19 PM
  • For example, this is one of them:

    "n = Double.TryParse(TextBox1.Text)".

    I don't know if I have done it correctly (I'm not familiar with "option strict on" method), just following what you mentioned.

            

    Abed_4321

    You are not following the instructions in the documentation I linked to.  You should have something like this.

    If Not Integer.TryParse(TextBox1.Text, n) Then
        MessageBox.Show("Enter valid integer for 'n'")
        Exit Sub
    End If
    'n will now contain the valid integer

    In this case, we use Integer.TryParse as n is an Integer. Use Double.TryParse when converting to Double.

    Wednesday, July 1, 2015 4:30 PM
  • It is hard to tell what you expect this code to do. I think what you want is the following. Note that I don't know how to calculate a LaGrange Interpolation, so I wasn't able to verify the calculation. Also note that I tried to give the variables and controls more meaningful names.

    Public Class Form1
        Private myList1 As New List(Of Double)
        Private myList2 As New List(Of Double)
    
        Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
            Dim num1, num2 As Double
            If Not Double.TryParse(Item1Box.Text, num1) Then
                MessageBox.Show("Enter a valid number for the first list")
                Exit Sub
            End If
            If Not Double.TryParse(Item1Box.Text, num2) Then
                MessageBox.Show("Enter a valid number for the second list")
                Exit Sub
            End If
            myList1.Add(num1)
            myList2.Add(num2)
        End Sub
    
        Private Sub CalcButton_Click(sender As Object, e As EventArgs) Handles CalcButton.Click
            Dim x As Double
            If Not Double.TryParse(XBox.Text, x) Then
                MessageBox.Show("Enter a valid number for X")
                Exit Sub
            End If
    
            ListBox1.Items.Add("x_i" & vbTab & "y_i")
            ListBox1.Items.Add("——————————")
            For num As Integer = 0 To myList1.Count - 1
                ListBox1.Items.Add(myList1(num).ToString & vbTab & myList2(num).ToString)
            Next
    
            TotalBox.Text = CalcTotal(x).ToString
        End Sub
    
        Function CalcTotal(x As Double) As Double
            Dim sum As Double
    
            For i As Integer = 0 To myList2.Count - 1
                Dim mlt As Double = 1
                For j As Integer = 0 To myList1.Count - 1
                    If j <> i Then mlt *= (x - myList1.Item(j)) / (myList1.Item(i) - myList1.Item(j))
                Next
                sum += mlt * myList2.Item(i)
            Next
    
            Return sum
        End Function
    
    End Class

    • Marked as answer by Abed_1234 Wednesday, July 1, 2015 5:19 PM
    Wednesday, July 1, 2015 5:08 PM
  • I have replied again to your original post with what I think you want your code to do.
    Wednesday, July 1, 2015 5:09 PM
  • I tried static and it solved the error problem but now it does not get out of that "if" and keeps unable the button1.

    Forget about enabling and disabling buttons until you have got the basic logic working. That is mostly cosmetic, and is only complicating your code.

    When you enter more than variable "n", it says : "Too many Entries".

    Then don't press the button.  When the message appears, it tells the user that it is time to move on to the next step (the calculation).   You are still thinking in terms of a sequential process.  That won't work with a Windows forms application.  You have to code in terms of user actions.

    If that's not working then perhaps you still don't have your user input validation working - you need to fix that first.

    Wednesday, July 1, 2015 11:10 PM