如何从数组中随机选择一个字符串

时间:2017-06-21 02:56:45

标签: arrays vb.net

我对编码很新,所以请原谅我。

我在数组中保存了一些示例字符串:

Dim intArray(0 To 2) As String
    intArray(0) = "I will be on time for class"
    intArray(1) = "I will be prepared for class"
    intArray(2) = "I will listen to the teacher and follow instructions"

    lblTestSWPB.Text = intArray(0)

我知道当我点击按钮生成(0)时它很有效 - 显然。有没有办法添加一些东西让标签在数组中随机显示一个字符串?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容:Random class

Dim rnd As New Random 'Make sure that you declare it as New, 
'otherwise, it thorws an Exception(NullReferenceException)
Dim intArray(0 To 2) As String

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    intArray(0) = "I will be on time for class"
    intArray(1) = "I will be prepared for class"
    intArray(2) = "I will listen to the teacher and follow instructions"
End Sub

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    lblTestSWPB.Text = intArray(rnd.Next(0, 3))
End Sub

请注意,rnd.Next是一个函数,它从最小值返回一个随机整数,包含下限,最大值是唯一上限。(感谢@Enigmativity进行更正。)Click this link if this answer is still unclear for you