从InputBox读取数据并插入1-D阵列

时间:2018-01-26 14:43:51

标签: arrays vb.net arraylist listbox

我试图从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

它无法正常工作。怎么了?有什么想法吗?

2 个答案:

答案 0 :(得分:0)

三个选项:

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())

答案 1 :(得分:0)

您应该做一些事情,特别是如果您想继续使用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