【问题标题】:Reading data from InputBox and insert into 1-D Array从 InputBox 读取数据并插入一维数组
【发布时间】:2018-07-05 22:16:12
【问题描述】:

我正在尝试从 InbutBox 插入数字并将它们保存到数组中以便稍后将它们显示到列表框中

我的 Vb.net 代码

Dim NumArray() As Double 
Dim ii As Integer = 10
    For ii = 0 To ii -1 
        NumArray = InputBox("Insert Number "+ii+"value", "Data Insertion", , , )
    Next

For ii = 0 To 10 -1
        ListBox1.Items.Add(NumArray(ii))
Next

它不工作。怎么了?有什么想法吗?

【问题讨论】:

    标签: arrays vb.net arraylist listbox


    【解决方案1】:

    您应该做一些事情,尤其是如果您想继续使用 InputBox。

    首先,您需要验证输入的值是有效的 Double。您可以通过实现Double.TryParse 方法来做到这一点。

    接下来,与其尝试将值输入到数组中,不如将它们直接添加到您的控件中。

    最后,我想指出您的 For/Next 循环永远不会执行。原因是因为首先,您将ii 的值从 10 覆盖为 0。接下来您尝试从 0 迭代到 -1,但不要更改循环的步长以向后迭代;默认情况下,For/Next 循环的步长为 +1。所以发生的情况是你的循环从 0 开始,检查它是否小于 -1,意识到它不是,然后什么也没有发生。

    以下是实施建议的示例:

    'Placeholder variables for the For/Next loop
    Dim dbl_value As Double
    Dim str_value As String
    
    'Loop from 1-10
    For ii As Integer = 1 To 10
        'Prompt for the currently iterated index's value
        str_value = InputBox("Insert number " & ii & " value", "Data Insertion")
    
        'Loop until the user enteres a valid Double
        Do Until Double.TryParse(str_value, dbl_value)
            'Inform the user that then did not follow instructions and re-prompt for a valid Double
            str_value = InputBox("That was not a valid Double. Please insert number " & ii & " value", "Data Insertion")
        Loop
    
        'Add the Double value to the ListBox
        ListBox1.Items.Add(dbl_value)
    Next
    

    【讨论】:

    • 非常感谢您的解释,非常有帮助,已接受
    【解决方案2】:

    三个选项:

    Dim ii As Integer = 10
    Dim NumArray(ii - 1) As Double 
    For i As integer = 0 To ii -1 
        NumArray(i) = InputBox("Insert Number " + i + "value", "Data Insertion", , , )
    Next
    
    ListBox1.Items.AddRange(NumArray)
    

    和:

    Dim ii As Integer = 10
    Dim NumArray As New List(Of Double)
    For i As Integer = 0 To ii -1 
        Dim input As Integer = InputBox("Insert Number "+ii+"value", "Data Insertion", , , )
        NumArray.Add(input)
        ListBox1.Items.Add(input)
    Next
    

    ListBox1.Items.AddRange(Enumerable.Range(0, 10).Select(Function(i) InputBox("Insert Number " + i + "value", "Data Insertion", , , )).ToArray())
    

    【讨论】:

    • 我想指出您的代码在 Option Strict 开启的情况下无法编译。此外,没有数据验证,当使用 InputBox 提示输入 String 值以外的内容时,这简直是愚蠢的。最后,在前两个示例中,当值应该直接添加到控件中时,首先将值存储到数组中。另外,在您的第一个示例中,您使用 AddRange,但在您的第二个示例中,您使用 Add。如果您要先将它们添加到集合中,最好只使用 AddRange,就像您在第一个示例中所做的那样。
    • 这很好用,谢谢帮助,我都在尝试,谢谢
    猜你喜欢
    • 2021-02-06
    • 2013-12-26
    • 2017-03-29
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多