简体   繁体   English

如何在 vb.net 中创建无限数组

[英]how do i create an infinate array in vb.net

I am trying to create a while loop that ends when someone types ".".我正在尝试创建一个 while 循环,该循环在有人键入“.”时结束。

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.提前致谢。

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) <> "."

您可以使用字典代替数组,也可以使用 x 变量作为键

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.如果它运行一段时间,您也可能会超出Integer数据类型所能容纳的范围。 Dim x As Long (or Decimal if you need even more) instead. Dim x As Long (如果您需要更多,则为Decimal )。

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.下面的代码应该首先定义大小为 1 的数组,然后您可以在循环中重新定义大小为 (x+1) 的数组。

    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. [更新 13/10/16 15:21] 将ReDim更改为ReDim Preserve以保留数组中的数据。 Thanks topshot谢谢顶图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM