首页 > 解决方案 > 随机字符串选择器(字符串名称完全相同,除了数字)

问题描述

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 分配给单词引号,所以每次它都会选择不同的引号?

标签: stringvb.netrandom

解决方案


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

如果您的列表随着时间的推移而演变(假设它存储在某个变量中),则您的方法不需要更新。例如,您的用户可以在不破坏您的代码的情况下将他自己的励志名言添加到列表中。


推荐阅读