我试图创建一个读取大型文档的程序,例如圣经,并输出多个随机行。我可以让它输出一个随机线,但没有其他线。
最终目标是使用用户输入来确定显示的行数。
这是我的代码:
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 :(得分:0)
我建议改进代码的一些事情。
实施Using。这将确保StreamReader
在完成后处理掉。它可以节省您的记忆,减少代码行数,从而提高可读性。
我会考虑使用Integer.TryParse:
将数字的字符串表示形式转换为其等效的32位有符号整数。返回值表示转换是否成功。
您只需使用一个StreamReader
并将所有行添加到List(Of String)
。
使用StringBuilder添加您的行,然后将其输出到最后的TextBox
。请注意,您必须导入System.Text
才能引用StringBuilder
类。
使用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
理想情况下,您可以将此代码放在按钮点击事件上。