我在visual basic中编写代码。该程序的目标是获得一个函数,在调用时从数组中随机选择一个字符串。问题是,当按钮调用它时,它不会选择不同的值。我不知道为什么会这样做。 还有谁知道如何在标签或文本中打印多行?这是我的代码。
Public Class lbl
Public Function Noun() As String
Dim rand As New Random
Dim index As Integer
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
Dim sentence As String ' used to build a sentence
index = rand.Next(5)
sentence = nouns(index)
Return sentence
End Function
Public Function outs(ByVal n1 As String) As String
Dim result = n1
Return result
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lblRandom.Text = outs(Noun()) & outs(Noun())
lblRandom1.Text = outs(Noun())
End Sub
答案 0 :(得分:1)
Public Shared Function RandomNumber(ByVal lowerBound As Integer, ByVal upperBound As Integer) As Integer
Return CInt(Math.Floor((upperBound - lowerBound + 1) * Rnd())) + lowerBound
End Function
Public Function Noun() As String
Dim rand As New Random
Dim index As Integer = -1
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
Dim sentence As String ' used to build a sentence
index = RandomNumber(0, 4)
sentence = nouns(index)
Return sentence
End Function
Public Function outs(ByVal n1 As String) As String
Dim result = n1
Return result
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
lblRandom.Text = outs(Noun()) & outs(Noun())
lblRandom1.Text = outs(Noun())
End Sub
答案 1 :(得分:0)
问题是每次调用Noun()函数时都会重新创建一个新的随机生成器。随机数生成器应该是一个全局变量。
答案 2 :(得分:0)
问题是.NET随机数生成器根据种子生成随机数。种子是基于当前系统日期和时间的整数。如果您快速连续多次调用随机数生成器,则可能会使用相同的种子并生成相同的“随机”数字。解决方案是在您希望生成随机数的过程之外声明Random对象,并将种子传递给从当前(随机)日期和时间构建的构造函数。
回答您的其他问题。如果文本包含回车符,则标签控件将自动换行文本。我在下面为lblRandom添加了一个回车。
要在文本框中包装文本,请将其Multiline属性设置为True。
@Aly El-Haddad发布的代码也可以使用,但它包含一些VB6遗留代码。我试图尽可能保持.NET。我还消除了多余的“出局”程序并使其灵活,以便您可以在“名词”数组中添加或删除元素。请注意,使用“index = rand.Next(5)”行,您将包含不存在的数组的元素5。从零开始的数组的上限为4,因此当随机数生成器返回5时,将抛出“索引超出数组范围”错误。
Private myRandom As New Random(CType(DateTime.Now.Ticks Mod Int32.MaxValue, Integer))
Private Function Noun() As String
Dim index As Integer
Dim nouns() As String = {"boy", "girl", "dog", "town", "car"}
index = myRandom.Next(nouns.GetLowerBound(0), nouns.GetUpperBound(0))
Return nouns(index)
End Function
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
lblRandom.Text = Noun() & Constants.vbNewLine & Noun()
lblRandom1.Text = Noun()
End Sub