2017-03-08 56 views
1

我正在嘗試製作一個讀取大文檔(例如聖經)的程序,並輸出多個隨機線。我可以得到它輸出一個隨機線,但沒有其他人。從大文檔輸出到文本框的隨機線

最終目標是有一個用戶輸入來確定顯示的行數。

這裏是我的代碼:

Public Class Form1 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     ' Dim howmanylines As Integer 
     ' howmanylines = InputBox("how many lines for paragrpah", "xd",,,) 
     'Dim count As Integer = 0 
     ' Do Until count = howmanylines 
     Dim sr As New System.IO.StreamReader("C:\Users\Dumpster Faggot\Desktop\bible.doc") 
     Dim sr2 As New System.IO.StreamReader("C:\Users\Dumpster Faggot\Desktop\bible.doc") 
     Dim sr3 As New System.IO.StreamReader("C:\Users\Dumpster Faggot\Desktop\bible.doc") 
     Dim xd As Integer = 0 
     Dim curline As Integer = 0 
     Dim random As Integer = 0 
     Do Until sr.EndOfStream = True 
      sr.ReadLine() 
      xd = xd + 1 
     Loop 
     sr.Dispose() 
     sr.Close() 
     Randomize() 
     random = Rnd() * xd 
     Do Until curline = random 
      TextBox1.Text = sr2.ReadLine 

      ' curline = curline + 1 
      Randomize() 
      random = Rnd() * xd 

      TextBox1.Text = sr3.ReadLine 

      curline = curline + 1 

      ' count = count + 1 
     Loop 
    End Sub 
End Class 
+0

你只有一個文本框來顯示結果嗎?您正在覆蓋每個循環的TextBox1.Text ...您需要一個列表或任何種類的集合 –

+0

是的,我只有一個文本框,但我將其更改爲多行將不工作? – Nosnhoj

+0

不,你不是追加內容,而是覆蓋它。試試這個:TextBox1.Text + = sr3.ReadLine –

回答

0

一對夫婦的事情,我會建議,以改善你的代碼。

  1. 實施Using。這將確保StreamReader完成後處置。它可以節省您必須記住的代碼行數,從而提高可讀性。

  2. 我會考慮使用Integer.TryParse

    一個數字的字符串表示形式轉換爲其32位有符號整數等效。返回值指示轉換是否成功。

  3. 您只需要使用一個StreamReader並將所有行添加到List(Of String)

  4. 使用StringBuilder也可以添加您的線條,然後在最後輸出到TextBox。請注意,您將不得不導入System.Text以引用StringBuilder類。

  5. 使用Random.Next

    返回一個隨機整數是一個指定的範圍內。

最終的結果會是這樣的:

txtLines.Text = "" 

Dim howManyLines As Integer = 0 
If Integer.TryParse(txtUserInput.Text, howManyLines) Then 

    Dim lines As New List(Of String) 

    Using sr As New StreamReader("C:\test\test.txt") 

     Do Until sr.EndOfStream() 
      lines.Add(sr.ReadLine) 
     Loop 

    End Using 

    Dim sb As New StringBuilder 
    Dim rnd As New Random() 

    For i = 0 To howManyLines - 1 
     Dim nextLine As Integer = rnd.Next(lines.Count - 1) 
     sb.AppendLine(lines(nextLine)) 
    Next 

    txtLines.Text = sb.ToString() 

End If 

你會非常將此代碼放置一個按鈕單擊事件。

+0

我不擅長編碼,但我會在哪裏添加這段代碼2? – Nosnhoj

+0

這取決於你想如何做到這一點。我點了一個'Button',然後從'TextBox'中讀取我輸入的數字。您可以在設計中添加一個'Button',並雙擊它以將處理程序添加到您的代碼中,然後添加此代碼。 – Bugs

+1

非常感謝您的幫助,真的很感激 – Nosnhoj