随机化列表索引超出范围后如何重复列表(字符串)

时间:2017-10-12 05:15:05

标签: vb.net exception

我是VB.net的新手程序员

所以我被困在这段代码中,这是随机名称生成器。



Private Function RandomLname(ByRef ranLname As String) As String

        Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("[pathto file.txt]", Encoding.Default)
        Dim lines As New List(Of String)
        Dim rnd As New Random()
        Dim line As Integer
        While reader.Peek <> -1
            lines.Add(reader.ReadLine())
        End While

        line = rnd.Next(lines.Count + 1)
        'the error shown in this line
        ranLname = lines(line)
        Return ranLname
        reader.Close()
        reader.Dispose()

    End Function
&#13;
&#13;
&#13;

经过几次运行后我一直收到ArgumentOutOfRangeException异常,有人可以帮帮我吗? 我需要脚本在它到达list.count时从头开始再次读取列表。任何人都可以有想法吗?

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

此:

line = rnd.Next(lines.Count + 1)

应该是这样的:

line = rnd.Next(lines.Count)

调用Random.Next时上限是独占的,集合中的最大索引比Count小1。

答案 1 :(得分:0)

试试这个:

Private Function RandomLname() As String

    Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader("[pathto file.txt]", Encoding.Default)
    Dim lines As New List(Of String)
    Dim rnd As New Random()
    Dim line As Integer
    While reader.Peek <> -1
        lines.Add(reader.ReadLine())
    End While

    line = rnd.Next(lines.Count)
    Return lines(line)
    reader.Close()
    reader.Dispose()

End Function

这是一个更简单的实现:

Private rnd As New Random()
Private Function RandomLname() As String
    Return File.ReadAllLines("[pathto file.txt]").OrderBy(Function(x) rnd.Next()).FirstOrDefault()
End Function