2017-06-21 5 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で乱数を生成する方法は非常に簡単です。明らかなキーワードをWebで検索するだけです。 '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

はありがとうございました!! –