2017-06-21 193 views
0

我对编码非常陌生,所以请原谅我。如何从数组中随机选择一个字符串

我曾在一个数组保存一些示例字符串:

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)它的工作原理 - obviously.Is有没有办法添加的东西,使标签从数组中随机显示一个字符串?

+2

从数组中获取元素的方法是提供元素的索引,您已经知道该元素的索引。获得随机元素的方法是生成一个随机数并将其用作索引。很容易找到如何在VB.NET中生成一个随机数。只需在网上搜索明显的关键字即可。只要确保忽略任何不使用Random类的结果。任何使用'Randomize'和'Rnd'的东西都应该被忽略,因为它基本上使用VB6风格的代码。 – jmcilhinney

+1

此外问题标题有点误导。这个问题本身与*产生随机字符串*无关。 –

回答

0

您可以使用类似:Random

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

+0

值得讨论的是'rnd.Next'中的最大值是_exclusive_最大值。 – Enigmativity

+0

啊,你是对的,我很抱歉,我不能简单地解释它... – Karuntos

+0

非常感谢! –

相关问题