从数组VB中随机生成一个元素

时间:2016-09-21 15:39:24

标签: arrays vb.net

我正在尝试创建一个程序,从cake rota数组中随机生成一个名称。我似乎无法让它发挥作用。目前,消息框显示一个随机数,而不是存储在数组中的名称。求救!

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim strNames(18) As String
        Dim frances, emma, piotr, jake, jess, jonah, john, flynn, will, nick As String

        strNames(0) = "frances"
        strNames(1) = "emma"
        strNames(2) = "piotr"
        strNames(3) = "jake"
        strNames(4) = "jess"
        strNames(5) = "jonah"
        strNames(6) = "john"
        strNames(7) = "flynn"
        strNames(8) = "will"
        strNames(9) = "nick"


        Dim rnum As Integer
        Dim temp As String
        For i = 0 To 18
            strNames(i) = i
        Next i

        Randomize()
        For i = 0 To 9
            rnum = Int(Rnd() * (UBound(strNames) - LBound(strNames) + 1) + LBound(strNames))
            temp = strNames(i)
            strNames(i) = strNames(rnum)
            strNames(rnum) = temp
        Next i


        For i = 0 To 9
            MessageBox.Show(strNames(i))
        Next i

    End Sub

1 个答案:

答案 0 :(得分:2)

该行

    For i = 0 To 18
        strNames(i) = i
    Next i

将strNames的值设置为数字。

取出并且似乎有效

    Dim strNames(18) As String
    Dim frances, emma, piotr, jake, jess, jonah, john, flynn, will, nick As String
    frances = "frances"
    emma = "emma"
    piotr = "piotr"
    jake = "jake"
    jess = "jess"
    jonah = "jonah"
    john = "john"
    flynn = "flynn"
    will = "will"
    nick = "nick"
    strNames(0) = frances
    strNames(1) = emma
    strNames(2) = piotr
    strNames(3) = jake
    strNames(4) = jess
    strNames(5) = jonah
    strNames(6) = john
    strNames(7) = flynn
    strNames(8) = will
    strNames(9) = nick


    Dim rnum As Integer
    Dim temp As String


    Randomize()
    For i = 0 To 9
        rnum = Int(Rnd() * (UBound(strNames) - LBound(strNames) + 1) + LBound(strNames))
        temp = strNames(i)
        strNames(i) = strNames(rnum)
        strNames(rnum) = temp
    Next i


    For i = 0 To 9
        MessageBox.Show(strNames(i))
    Next i