在vb.net中,如何声明数组而不提及大小?并随着输入的到来改变大小?
Sub Main()
Dim s() As String
ReDim Preserve s(UBound(s) + 1)
Dim counter As Integer
counter = 0
Do
Console.WriteLine("Enter Name: ")
s(counter) = Console.ReadLine()
counter = counter + 1
Loop Until counter <> -1
For Each arr In s
Console.WriteLine(arr)
Next
End Sub
最终模块
答案 0 :(得分:2)
尝试使用列表而不是数组。
Dim s As New List(Of String)
Dim inp As String
Do
Console.WriteLine("Enter Name: ")
inp = Console.ReadLine
If inp <> "" Then
s.Add(inp)
End If
Loop Until inp = ""
For Each itm As String In s
Console.WriteLine(itm)
Next
答案 1 :(得分:1)
您需要ReDim Preserve
插入每个名称之前:
Sub Main()
Dim s() As String
Dim response As String
Dim counter As Integer = 0
Do
Console.Write("Enter Name (enter `quit` to stop): ")
response = Console.ReadLine()
If response.ToLower <> "quit" Then
ReDim Preserve s(counter)
s(counter) = response
counter = counter + 1
End If
Loop While response.tolower <> "quit"
If counter > 0 Then
For Each arr In s
Console.WriteLine(arr)
Next
End If
Console.Write("Press Enter to quit")
Console.ReadLine()
End Sub