Dim r As MySqlDataReader
Dim i As Integer = 0
Dim temp() As Integer = {}
Dim txtQ() As TextBox = {txtQ1, txtQ2, txtQ3, txtQ4, txtQ5, txtQ6, txtQ7, txtQ8, txtQ9, txtQ10}
Dim cbA() As CheckedListBox = {cbA1, cbA2, cbA3, cbA4, cbA5, cbA6, cbA7, cbA8, cbA9, cbA10}
con.Open()
cmd = New MySqlCommand("select * from tbexam", con)
r = cmd.ExecuteReader
While r.Read
If i <= 9 Then
Randomize()
Dim j As Integer = CInt(Int(9 * Rnd()))
txtQ(j).Text = r.GetString("exam_question")
cbA(j).Items.Clear()
cbA(j).Items.Add("a) " & r.GetString("exam_ans_a"))
cbA(j).Items.Add("b) " & r.GetString("exam_ans_b"))
cbA(j).Items.Add("c) " & r.GetString("exam_ans_c"))
cbA(j).Items.Add("d) " & r.GetString("exam_ans_d"))
i = i + 1
End If
End While
答案 0 :(得分:1)
当你在j
中放置一个随机数时,它(非常接近)是0到9之间的一个随机数。这相当于滚动一个十边骰子。您认为如果您要将其滚动十次,您将获得0到9中的每一个中的一个值的可能性是多少?很低。你实际得到的是:2,0,8,2,5,1,7,6,1,4。这个序列包含2和1的重复,并且不出现值3和9。这就是你的重复和差距来自的地方。
您可以尝试的一个选项是按顺序填充数组,然后将其随机播放。
Dim r As MySqlDataReader
Dim i As Integer = 0
Dim temp() As Integer = {}
Dim txtQ() As TextBox = {txtQ1, txtQ2, txtQ3, txtQ4, txtQ5, txtQ6, txtQ7, txtQ8, txtQ9, txtQ10}
Dim cbA() As CheckedListBox = {cbA1, cbA2, cbA3, cbA4, cbA5, cbA6, cbA7, cbA8, cbA9, cbA10}
con.Open()
cmd = New MySqlCommand("select * from tbexam", con)
r = cmd.ExecuteReader
' Read the Q&As into the arrays in the order they appear in the DB
While r.Read
If i <= 9 Then
txtQ(i).Text = r.GetString("exam_question")
cbA(i).Items.Clear()
cbA(i).Items.Add("a) " & r.GetString("exam_ans_a"))
cbA(i).Items.Add("b) " & r.GetString("exam_ans_b"))
cbA(i).Items.Add("c) " & r.GetString("exam_ans_c"))
cbA(i).Items.Add("d) " & r.GetString("exam_ans_d"))
i = i + 1
End If
End While
' Re-order the arrays by swapping each element with another, randomly selected element.
' Start with i at the count of the elements read in the last loop and work down.
Dim n as Integer = i - 1
While i > 0
Dim j As Integer = CInt(Int(n * Rnd()))
i = i - 1
' Swap elements i and j of the arrays
Dim tmpQ As TextBox = txtQ(i)
txtQ(i) = txtQ(j)
txtQ(j) = tmpQ
Dim tmpA() As CheckedListBox = cbA(i)
cbA(i) = cbA(j)
cbA(j) = tmpA
End While
这可以简化和抽象,但你明白了。
答案 1 :(得分:0)
使用随机数生成很难避免重复输入,但您可以避免空条目。你得到空条目,因为你生成随机数并用该id获取问题,不幸的是,id始终在数据库中不可用。首先,从数组中的数据库中获取所有ID,并生成从0到数组长度的随机数。并选择数组键的id值。