Reputation:
Dim rnd As New Random
Dim quote1, quote2, quote3 As String
Dim int As Integer
int = rnd.Next(1, 3)
quote1 = "never give up"
quote2 = "always believe in yourself"
quote3 = "always follow your dreams"
MessageBox.Show("quote" & int)
Hey, can somebody please tell me, how I can assign the int to the word quote, so every time it would pick a different quote?
Upvotes: 0
Views: 51
Reputation: 3207
With only 3 quotes you can do something like
Dim quoteIndex As Integer = Rnd.Next(1, 3)
Dim quote As String = ""
Select Case quoteIndex
Case 1
quote = quote1
Case 2
quote = quote2
Case 3
quote = quote3
End Select
MessageBox.Show(quote)
But in all honesty it's a quite lame solution, more akin to ninja code than to good practices. Instead, you should use an array or a list (which can be created inside this method or come from somewhere else like an overload or a modal variable):
Dim quoteList As New List(Of String)
quoteList.AddRange({"never give up", "always believe in yourself", "always follow your dreams", "something else"})
Dim quoteChoosen As Integer = Rnd.Next(0, quoteList.Count) 'this array start at zero
MessageBox.Show(quoteList(quoteChoosen)) '
If your list evolves over time (assuming that it's stored in a variable somewhere), your method won't need to be updated. Your user could add his own motivational quotes to the list without breaking your code, for an example.
Upvotes: 1
Reputation: 1280
As your code it written, you're showing a string value in the MessageBox. The string is being appended to, so it is dynamic and random, but it's still a string.
To get the affect I think you're looking for, you would need to use your random value as a pointer of some sort to reference a variable value. Using an array is probably the most straight-forward way to do that with this code. Instead of having 3 distinct quote strings values, you could create an array of strings...something like
quote = new string[]
where
quote[0] = "never give up"
then you could do something like MessageBox.Show(quote[int])
Upvotes: 0