Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何从数组中随机选择字符串_Arrays_Vb.net - Fatal编程技术网

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

Arrays 如何从数组中随机选择字符串,arrays,vb.net,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.

我对编码很陌生,所以请原谅我

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

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)生成时,它会工作-很明显。是否有方法添加一些内容,使标签从数组中随机显示字符串?

您可以使用类似于:
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的更正。)

从数组中获取元素的方法是提供元素的索引,这是您已经知道的方法。获取随机元素的方法是生成一个随机数并将其用作索引。在VB.NET中很容易找到如何生成随机数。只需在网上搜索明显的关键词。只需确保忽略不使用
Random
类的任何结果。任何使用
Randomize
Rnd
的都应该被忽略,因为它基本上使用的是VB6风格的代码。此外,问题标题有点误导。问题本身与生成随机字符串无关。值得讨论的是,
rnd.Next
中的最大值是唯一的最大值。