随机数介于1到20之间,不包括已选中的数字

时间:2013-11-30 16:43:41

标签: vb.net random

我正在尝试创建一个多次运行的随机数生成器,但是每次将之前选择的数字添加到数组列表中,然后从随机函数中排除数组中的数字。

有什么想法吗?

我尝试了这个,但它在一行中完成了所有但我需要将它分开以使用数字调用函数

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    TextBox1.Text = ""


    For x = 0 To 5
    Start:
        Randomize()
        intNumber = Int((20 * Rnd()) + 1)
        For y = 0 To 5
            If intNumber = arrNumber(y) Then
                GoTo Start
            End If
        Next y
        arrNumber(x) = intNumber

    Next x
    For i = 0 To 5
        TextBox1.Text = TextBox1.Text & (arrNumber(i)) & " , "

    Next


End Sub

1 个答案:

答案 0 :(得分:0)

这里有一个示例代码,您应该能够轻松地适应您的确切要求。它包括两个按钮(newRandomreset):一个用于生成新的随机数(通过MessageBox显示),另一个用于删除存储所有已出现的数字的列表远。

Dim alreadyPicked As List(Of Integer) = New List(Of Integer) 

Private Sub newRandom_Click(sender As System.Object, e As System.EventArgs) Handles newRandom.Click

    Dim curNumber As Integer
    If (alreadyPicked.Count < 20) Then
        Dim rand As Random = New Random
        Do
            curNumber = rand.Next(1, 20)
        Loop While (alreadyPicked.Contains(curNumber))
    End If


    If (curNumber > 0 AndAlso Not alreadyPicked.Contains(curNumber)) Then
        alreadyPicked.Add(curNumber)
        MessageBox.Show("The new random number is: " & curNumber.ToString())
    Else
        MessageBox.Show("Error")
    End If

End Sub

Private Sub reset_Click(sender As System.Object, e As System.EventArgs) Handles reset.Click

    alreadyPicked = New List(Of Integer)

End Sub