随机字符串选取器(字符串名称完全相同,除了数字)


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)

嘿,有人可以告诉我,我如何将 int 分配给单词 quote,所以每次它都会选择一个不同的报价?

只需 3 个引号,您就可以执行以下操作

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)

但老实说,这是一个相当蹩脚的解决方案,更类似于忍者代码而不是良好实践。相反,您应该使用数组或列表(可以在此方法中创建,也可以来自其他地方,如重载或模态变量(:

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))  '

如果列表随时间推移而变化(假设它存储在某处的变量中(,则无需更新方法。例如,您的用户可以将自己的激励语录添加到列表中,而不会破坏您的代码。

在编写代码时,您将在消息框中显示一个字符串值。 字符串被追加到,因此它是动态和随机的,但它仍然是一个字符串。

为了获得我认为您正在寻找的影响,您需要使用随机值作为某种指针来引用变量值。 使用此代码使用数组可能是最直接的方法。 您可以创建一个字符串数组,而不是拥有 3 个不同的引号字符串值......类似的东西

quote = 新字符串[]

哪里

quote[0] = "永不放弃">

然后你可以做一些类似 MessageBox.Show(quote[int](

最新更新