【问题标题】:how do i create an infinate array in vb.net如何在 vb.net 中创建一个无限数组
【发布时间】:2016-10-13 11:52:36
【问题描述】:

我正在尝试创建一个当有人键入“.”时结束的 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.

提前致谢。

【问题讨论】:

  • 在增加 x 后立即尝试 ReDim Preserve stuff(x)
  • 使用列表而不是数组。
  • 这是一个示例,说明为什么在项目数量不同时应使用 List 等通用集合而不是数组 stackoverflow.com/a/34453165/1383168

标签: arrays vb.net loops while-loop


【解决方案1】:

使用列表

    Dim stuff As New List(Of String)
    Do
        Console.WriteLine("input stuff end with .")
        stuff.Add(Console.ReadLine())
    Loop While stuff(stuff.Count - 1) <> "."

【讨论】:

    【解决方案2】:

    基本上,您的代码的问题在于您的数组。下面的代码应该完成最初定义大小为 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
    

    希望对你有帮助

    [2016 年 13 月 10 日更新 15:21] 将 ReDim 更改为 ReDim Preserve 以保留数组中的数据。谢谢上图

    【讨论】:

    • 不指定Preserve他会丢失数组中的数据
    • 感谢@topshot 相应地改变了答案
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      x = x + 1
      ReDim Preserve stuff(x) 'add this line
      Console.WriteLine("input stuff end with .")
      

      如果运行一段时间,您也可能会超出 Integer 数据类型所能容纳的范围。改为Dim x As Long(或Decimal,如果您需要更多)。

      【讨论】:

        猜你喜欢
        • 2010-11-02
        • 2012-04-02
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多