1

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.

gamemage49
  • 13
  • 2
  • 2
    Try `ReDim Preserve stuff(x)` right after you have incremented **x** – Bugs Oct 13 '16 at 11:58
  • 1
    Use List instead of an array. – dbasnett Oct 13 '16 at 12:35
  • 1
    Here is one example of why you should use generic collection like [`List`](https://msdn.microsoft.com/en-us/library/6sh2ey19#Anchor_8) instead of array when the number of items varies http://stackoverflow.com/a/34453165/1383168. – Slai Oct 13 '16 at 13:11

4 Answers4

4

Use a List

    Dim stuff As New List(Of String)
    Do
        Console.WriteLine("input stuff end with .")
        stuff.Add(Console.ReadLine())
    Loop While stuff(stuff.Count - 1) <> "."
dbasnett
  • 11,334
  • 2
  • 25
  • 33
0

You can use instead a dictionary instead of an array, you can use your x variable as your key

romulus001
  • 318
  • 3
  • 15
0
x = x + 1
ReDim Preserve stuff(x) 'add this line
Console.WriteLine("input stuff end with .")

You will also likely exceeding what can fit in an Integer data type if it runs a while. Dim x As Long (or Decimal if you need even more) instead.

topshot
  • 885
  • 6
  • 21
0

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

Bugs
  • 4,491
  • 9
  • 32
  • 41
littleswany
  • 473
  • 2
  • 6
  • 18