有一种方法可以从vb.net中的数组生成随机字符串而无需重复

问题描述 投票:0回答:1

我要尝试创建的程序是在加载表单时显示来自数组的人的随机描述的程序。我试过了,但它只输出一个字符串,多数民众赞成在RAND(1)

Public Class male
Public Property stringpass
Private Sub male_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim RAND(2)
    RAND(0) = "Nobody's perfect of course and Frederick has plenty of less favorable characteristics too." & Environment.NewLine & " His pompous nature and desperation tend to get in the way even at the best of times." & Environment.NewLine & "Fortunately his grace is there to relift spirits when needed."

    RAND(1) = "Animal"
    RAND(2) = "Construct"
    Label2.Text = RAND(rnd)

    Label1.Text = stringpass

End Sub
vb.net
1个回答
0
投票

仅在类级别声明一次Random类。我使用了List(Of T),因此您可以轻松地添加到列表中,而无需更改数组的尺寸。 Random类的.Next方法返回一个数字,其中包括第一个参数,而第二个参数除外。

您可能会多次获得琴弦。毕竟,您只有3个选择。

Public Class male
    Public Property stringpass As String
    Private rnd As New Random

    Private Sub male_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim RAND As New List(Of String)
        RAND.Add("Nobody's perfect of course and Frederick has plenty of less favorable characteristics too." & Environment.NewLine & " His pompous nature and desperation tend to get in the way even at the best of times." & Environment.NewLine & "Fortunately his grace is there to relift spirits when needed.")
        RAND.Add("Animal")
        RAND.Add("Construct")
        Label2.Text = RAND(rnd.Next(0, RAND.Count))
        Label1.Text = stringpass
    End Sub
End Class
© www.soinside.com 2019 - 2024. All rights reserved.