【发布时间】:2014-10-16 17:39:45
【问题描述】:
好的,使用 Visual Basic(在 Visual Studio Express 2013 中,如果有影响的话)。我正在尝试创建一个函数,该函数从文本文件中获取名字列表,并将每一行插入到数组中的索引中。我得到的是特定索引,而不是分配给该索引的字符串。
Private Sub btnAutofill_Click(sender As Object, e As EventArgs) Handles btnAutofill.Click
Dim ranFname As String = RandomFname(ranFname)
Dim ranLname As String = RandomLname(ranLname)
txtCustFname.Text = ranFname
txtCustLname.Text = ranLname
End Sub
Private Function RandomFname(ByRef ranFname As String) As String
Dim userPath As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim fname() As String
Dim rand As New Random()
fname = IO.File.ReadAllLines(userPath & "\OneDrive\Coding\Visual Studio\firstNames.txt")
ranFname = rand.Next(0, fname.Length - 1)
Return ranFname
End Function
Private Function RandomLname(ByRef ranLname As String) As String
Dim userPath As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim lname() As String
Dim rand As New Random()
lname = IO.File.ReadAllLines(userPath & "\OneDrive\Coding\Visual Studio\lastNames.txt")
ranLname = rand.Next(0, lname.Length - 1)
Return ranLname
End Function
现在,当我单击自动填充按钮时,我的文本框不再显示:
名字:Mary 姓:Jones
我明白了:
名字:68 姓氏:68
我也不知道为什么每次都是一样的数字,应该是随机的。
很明显,我走错了路。有人介意帮助我吗?
【问题讨论】:
-
不要每次都重新创建 Random 对象,这是导致数字问题的原因。创建一次并将其作为参数传递。此外,我将文件名作为参数传递并具有单一名称功能,因为它们只是在不同的文件上执行相同的操作。
-
用
Return lname (ranLname)替换Return ranLname
标签: arrays vb.net function random visual-studio-2013