gamemage49 gamemage49 - 1 month ago 8
Vb.net Question

how do i create an infinate array in vb.net

I am trying to create a while loop that ends when someone types ".".

My code is as follows and I get the error that follows the code:

Dim x, y As Integer
Dim stuff(x) As String
y = 1
x = 0
While y = 1
x = x + 1
Console.WriteLine("input stuff end with .")
stuff(x - 1) = Console.ReadLine()
If stuff(x - 1) = "." Then
y = 0
End If

End While


The error message:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in practise.exe

Additional information: Index was outside the bounds of the array.


Thanks in advance.

Answer

Basically the issue with your code is your array. The below code should do the trick initially defining the array with size 1, then you can redefine the array with size (x+1) within the loop.

    Dim x, y As Integer
    Dim stuff(1) As String
    y = 1
    x = 0
    While y = 1
        x = x + 1
        Console.WriteLine("input stuff end with .")
        stuff(x - 1) = Console.ReadLine()
        If stuff(x - 1) = "." Then
            y = 0
        End If
        ReDim Preserve stuff(x + 1)

    End While

Hope this helps

[UPDATE 13/10/16 15:21] Changed ReDim to ReDim Preserve to preserve the data in the array. Thanks topshot