【问题标题】:Randomising String Array随机化字符串数组
【发布时间】:2016-01-04 20:22:44
【问题描述】:

我正在创建一个充当问题球的程序。用户会问一个问题,然后程序会给出随机响应。我正在努力让程序从我制作的数组中随机生成响应。我不知道如何做字符串数组并使其随机化。我尝试了很多东西,但都没有奏效,所以这是我的基本代码。

Sub Main()

Dim userquestion As String   
Dim questions(0 To 9) As String
Console.WriteLine("Simply enter a question and it will be answered.")
userquestion = Console.ReadLine()

questions(0) = "Most Likely."
questions(1) = "Outlook Good"
questions(2) = "Yes"
questions(3) = "Sorry, I'm confused ask again later "
questions(4) = "I can't predict now"
questions(5) = "Try to concentrate more so I can use to answer the question."
questions(6) = "Don't COunt on it"
questions(7) = "Yes Do it it will work !"
questions(8) = "My reply is no"
questions(9) = "Sorry, I was sleeping I forgot the question"

Console.WriteLine("The answer is ")

Console.WriteLine("Did you like the answer ? ")
Console.ReadLine()

【问题讨论】:

  • Dim questions(0 To 9) As String --> Dim questions(9) As String

标签: arrays vb.net string random


【解决方案1】:

您需要使用Random 对象。生成随机数,然后在显示时将该随机数用作数组的索引。比如:

Dim randNumGenerator As New Random()
Dim randNum As Integer

randNum = randNumGenerator.Next(0, 10) 'Generates a random number from 0 to 9 (the array indexes)

Console.WriteLine(questions(randNum))

【讨论】:

  • 最佳实践是 randNumGenerator 应该共享
  • 同样,上面的数字是排他的,而下面的数字是包含的,所以应该是randNumGenerator.Next(0, 10) 来给出0-9之间的数字
  • @MattWilko 同意。只是做了一个简单的例子,但我应该指定的。
  • @MattWilko 我根据您的评论编辑并修复了randNumGenerator.Next 行。很好的收获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
相关资源
最近更新 更多