2017-03-08 49 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