Question Random event

john19992010

Member
Joined
Jun 8, 2014
Messages
5
Programming Experience
1-3
Hi, this is my first post to the forums so i wasn't sure which thread section to post it in. My question is, i have a DLA (Digital Life Assistant ) program like JARVIS that generates random jokes, i want the user to speak and it reads out one of fifty jokes already programmed into it. Originally, I was using this code:

Case Is = "TELL ME A JOKE"
Select Case Number
Case Is = 1
Jarvis.speak(joke)
Case Is = 2
Jarvis.speak(joke)
Case Is = 3
Jarvis.speak(joke)
Case Is = 4
Jarvis.speak(joke)


and so on until fifty. i believed that the program would select a random case number and perform the code under it however i realised that this isn't in fact the right code but one for testing variables or something. Can someone help me please
 
Something like this:

VB.NET:
       Dim randvar As New Random()
        Dim randnum As Integer
        Dim joke As String   'or whatever type it is
        randnum = randvar.Next(1, 5)  'for 50 jokes, use randvar.Next(1, 51)
        Select Case randnum
            Case Is = 1
                joke = "myjoke1"
            Case Is = 2
                joke = "myjoke2"
            Case Is = 3
                joke = "myjoke3"
            Case Is = 4
                joke = "myjoke4"
            ' etc
        End Select
        Jarvis.speak(joke)

If you have the jokes in an array, that makes it much shorter. Instead of Select Case, you can simply do:

VB.NET:
        Dim myjoke(50) As String   'or whatever type it is
        Dim randvar As New Random()
        Dim randnum As Integer
        randnum = randvar.Next(1, 51)  'for 50 jokes
        joke = myjoke(randnum)
        Jarvis.speak(myjoke)
 
Thanks solitaire, I used the top code. It worked fine apart from the last line, Jarvis.speak (joke), it says:


"Variable 'joke' is used before it has been assigned a value. A null reference exception could result at runtime.


I am familiar with this error but i don't want to try anything before i make sure its right. how would I fix this
 
Back
Top