-1

我需要以下格式的随机数生成器:65X XXX XXXX;不包括 1 和 4。这是我完成第一个 VB.net 项目之前的最后一步。如果您能提供帮助,请回复。

下面是我的黑醋栗代码,除了不排除数字外,它的效果很好。如果您能帮助编辑我的代码,我将不胜感激.. 谢谢!

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Dim rnd As New Random
Dim str1, str2, str3 As String
str1 = "65" & rnd.Next(0, 9)
str2 = rnd.Next(100, 999)
str3 = rnd.Next(1000, 9999)
ListBox1.Items.Add(str1 & " " & str2 & " " & str3)
End Sub
4

1 回答 1

1

创建一个随机生成器,而不是在每次计时器点击时创建一个新生成器。随机生成器使用从系统时钟创建的值作为种子,因此如果您创建它们的时间太近,它们将生成相同的随机数系列。此外,以设定的时间间隔创建它们可能会在随机数中产生不需要的模式。

Private rnd As New Random

您可以使用从特定字符集创建随机字符串的函数:

Private Function RandomString(ByVal chars As String, ByVal len As Integer) As String
  Dim result As String = ""
  For i As Integer = 1 to len
    result += chars.Substring(rnd.Next(chars.Length), 1)
  Next
  Return result
End Function

(注意:+=用于连接字符串只能用于短字符串。对于超过 20 个字符的任何内容,您应该使用 aStringBuilder或字符数组。)

现在您可以使用该函数来创建字符串:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
  Dim chars As String = "02356789"
  Dim str As String = "65" & _
    RandomString(chars, 1) & " " & _
    RandomString(chars, 3) & " " & _
    RandomString(chars, 4)
  ListBox1.Items.Add(str)
End Sub
于 2014-05-31T00:58:13.107 回答