[Solved] How to display random ques from text file in vb?


I would make a class “question” like this:

public Class Question

public questionas String
public answer1 as String
public answer2 as String
public answer3 as String
public answer4 as String
public correctAnswer as integer

public sub new(que as string, a1 as string, a2 as string, a3 as string, a4 as string, answer as integer)
    question= que
    answer1=a1
    answer2=a2
    answer3=a3
    answer4=a4
    correctAnswer=answer
end sub


end Class

Now load all your questions in the programm like this:

Imports System
Imports System.IO

Class MainWindow
    private listQuestions as List(Of Question)

Public Sub window_loaded() handles MainWindow.loaded
    listQuestions = loadAllQuestions()        
End Sub



private function loadAllQuestions() as List(Of Question)
Dim str() As String
    Try
        ' Open the file using a stream reader.
        Using sr As New StreamReader("example.txt")
            Dim line As String
            ' Read the stream to a string and write the string to the console.

            line = sr.ReadToEnd()
            Str = line.Split(vbNewLine)
        End Using
    Catch e As Exception
        Console.WriteLine("The file could not be read:")
        Console.WriteLine(e.Message)
    End Try

   'So now put the questions in your list:

    dim list as new List(Of Question)

    For i = 0 to str.count - 1
        if (i+1) mod 5 = 0 then 'is divible without rest by 6
           list.add(new Question(str(i-5), str(i-4), str(i-3), str(i-2), str(i-1), str(i))
        end if

    next

    return list



end sub

'Load a random question:
private sub btNext_click() handles btNext.click()
    dim ranQuestion as Question

    dim r as new random

    ranQuestion = listFragen.item(r.next(0,listQuestions.count))


End Class

Hope i could help you. To prevent that the programm can show the same question again its your job 🙂

1

solved How to display random ques from text file in vb?