简体   繁体   English

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

[英]How to randomly select a string from an array

I am very new to coding so please forgive me. 我对编码非常陌生,请原谅我。

I have saved some example strings in an array: 我已经在数组中保存了一些示例字符串:

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)

I know that it works when I click the button to generate for (0) - obviously.Is there a way to add something to make the label display a string at random from the array? 我知道当单击按钮生成(0)时它有效-很明显,是否有办法添加一些东西以使标签从数组中随机显示一个字符串?

You may use something like: Random class 您可以使用类似以下的方法: 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

Note that rnd.Next is a Function that returns a random Integer from the minimum is the inclusive lower bound and the maximum is the exclusive upper bound.(Thanks to @Enigmativity for the correction.) Click this link if this answer is still unclear for you 请注意, rnd.Next是一个函数,它从最小值为包含下限,最大值为排除上限返回随机整数。(感谢@Enigmativity进行更正。) 如果此答案尚不清楚,请单击此链接。您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM