2017-10-12 98 views
0

我爲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

我不斷收到ArgumentOutOfRangeException異常幾年運行後,任何人都可以幫助我嗎? 我需要腳本從頭再次讀取列表,當它到達list.count任何人都可以有想法?

任何幫助,將不勝感激。

+0

嘗試'線= rnd.Next(lines.Count)'。 – Enigmativity

+0

你的代碼有一個主要的缺陷,那就是你在'Return'語句之後關閉了文本文件,即你根本沒有關閉它。您應該使用'Using'語句打開它,然後隱式關閉它,而不管該方法如何結束。 – jmcilhinney

+0

我已經刪除了reader.Close()和reader.Dispose(),但它不會重新排列列表。即使當我刪除(+ 1)列表不會產生任何結果60 +結果書面 – Hyuichiro

回答

1

此:

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

應該是這樣的:

line = rnd.Next(lines.Count) 

主叫Random.Next和集合中的最大索引大於Count少1時的上限是排他性的。

+0

當上限達到時,我可以做些什麼來重新從頭開始讀取列表?堅持這一點。因爲我的名單中包含了148個名字,而且我隨機使用了兩個名字作爲情侶。但是在60對夫婦之後,它應該在74對夫妻中完成。任何想法? – Hyuichiro

+0

如果你有一個新的問題要問,然後問一個新的問題。不要捎帶到這一個。 – jmcilhinney

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