string - 随机字符串选择器(字符串名称完全相同,除了数字)
问题描述
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 分配给单词引号,所以每次它都会选择不同的引号?
解决方案
只需 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)) '
如果您的列表随着时间的推移而演变(假设它存储在某个变量中),则您的方法不需要更新。例如,您的用户可以在不破坏您的代码的情况下将他自己的励志名言添加到列表中。
推荐阅读
- python - 抓取不起作用 - InvalidSelectorException:消息:无效选择器:指定了无效或非法的选择器
- kubernetes - 不在k8s中加载秘密
- javascript - 使用 npm 中的 react-gallery 组件从 flickr api url 渲染图像
- python - 打印特定组合
- java - Java中使用锁的生产者/消费者线程示例
- php - 如何在php中模拟POST表单提交?
- javascript - 异步函数不等待结束
- pyinstaller - 我正在尝试使用 pip 安装 Pyinstaller v 4.3,但出现未找到模块错误
- php - CKFinder tempDirectory 不能在 Linux 上运行?
- azure - Snowflake 中的外部 Azure 舞台