[英]how do i create an infinate array in vb.net
我正在尝试创建一个 while 循环,该循环在有人键入“.”时结束。
我的代码如下,我收到代码后面的错误:
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
错误信息:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in practise.exe
Additional information: Index was outside the bounds of the array.
提前致谢。
使用列表
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 .")
如果它运行一段时间,您也可能会超出Integer
数据类型所能容纳的范围。 Dim x As Long
(如果您需要更多,则为Decimal
)。
基本上你的代码的问题是你的数组。 下面的代码应该首先定义大小为 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
希望这可以帮助
[更新 13/10/16 15:21] 将ReDim
更改为ReDim Preserve
以保留数组中的数据。 谢谢顶图
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.