随机化文本文件中的行

时间:2016-03-02 13:33:07

标签: vb.net

我有一个文本文件,用于多选问题和答案表单。我想一次调用4行,并在标签中输出这4个值。出于演示目的,每行将有一个单词,因此用户必须在选项1 - 4之间进行选择,例如

  1. 红色
  2. 绿色
  3. 黄色
  4. 但是我想为3个标签随机选择4个值,但我的文件将有6个标签的足够值,这样每次用户加载程序时它都不会重复这些问题。

    Here是我的文本文件

    Public Class Form1
    Dim rand As New Random
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim QuestionFile As New IO.StreamReader(CurDir() & "\" & "Questions.txt")
        Dim fileContentsQ As String = QuestionFile.ReadToEnd
        Dim fileListQ As New List(Of String)
        For Each Str As String In fileContentsQ.Split(CChar(vbCrLf))
            fileListQ.Add(Str)
        Next
        Dim randItem As Integer = rand.Next(0, fileListQ.Count - 1)
        Label1.Text = (fileListQ.Item(randItem))
        fileListQ.RemoveAt(randItem)
        'removes item from list so that it isn't repeated
        Dim randItem2 As Integer = rand.Next(0, fileListQ.Count - 1)
        Label2.Text = (fileListQ.Item(randItem))
        fileListQ.RemoveAt(randItem)
        Dim randItem3 As Integer = rand.Next(0, fileListQ.Count - 1)
        Label3.Text = (fileListQ.Item(randItem))
        fileListQ.RemoveAt(randItem)
    End Sub
    

    结束班

    问题是,当我希望每个标签一次显示4个单词时,每个标签只显示一个单词/行,例如Label1可能(全部在彼此之下):

      


      蓝
      绿色
      黄

1 个答案:

答案 0 :(得分:0)

尝试一下:

Dim lst As New List(Of String)(IO.File.ReadAllLines("Archivo.txt"))
Dim nst As New List(Of String)
Randomize()
While lst.Count > 0
     Dim rdi As Integer = CInt(Math.Floor(Rnd() * lst.Count))
     nst.Add(lst(rdi))
     lst.RemoveAt(rdi)
End While
IO.File.WriteAllLines("Archivo.txt", nst.ToArray, Encoding.Unicode)

希望有帮助。