所以这只是我的问题VB.Net grade distribution exercise
的延续但我现在要做的是在点击按钮时交换或随机化他们的位置。
所以这就是我正在做的事情:
If txtGrade.Text <> "" Then
If CDbl(txtGrade.Text) Then
txtA.Text = (CDbl(txtGrade.Text) * 40) / 100
txtB.Text = (CDbl(txtGrade.Text) * 20) / 100
txtC.Text = (CDbl(txtGrade.Text) * 30) / 100
txtD.Text = (CDbl(txtGrade.Text) * 10) / 100
End If
End If
更新 我把上面的代码放在txtGrade_TextChanged事件
上但我真的不知道如何随机化他们的位置。有任何想法吗?感谢。
答案 0 :(得分:2)
使用Random
类:(编辑后显示更简洁的版本)
Dim grade As Double
If Double.TryParse(txtGrade.Text, grade) Then
Dim values = {(grade * 40 / 100).ToString(), (grade * 20 / 100).ToString(), (grade * 30 / 100).ToString(), (grade * 10 / 100).ToString()}
FillRandomControlText({txtA, txtB, txtC, txtD}, values)
End If
用这种方法:
Shared Sub FillRandomControlText(txtControls As IList(Of TextBox), values As IList(Of String))
Dim rnd = New Random()
Dim txt As TextBox
Dim selectedControls = New List(Of Control)(txtControls.Count)
For i As Int32 = 0 To txtControls.Count - 1
Do
txt = txtControls(rnd.Next(txtControls.Count))
Loop While selectedControls.Contains(txt)
selectedControls.Add(txt)
txt.Text = values(i)
Next
End Sub
<击> 昏暗等级为双倍 Dim rnd = New Random() 昏暗控件= {txtA,txtB,txtC,txtD} Dim selectedControls =新列表(控制中) Dim txt As TextBox
If Double.TryParse(txtGrade.Text, grade) Then
Do
txt = controls(rnd.Next(controls.Length))
Loop While selectedControls.Contains(txt)
selectedControls.Add(txt)
txt.Text = (grade * 40 / 100).ToString()
Do
txt = controls(rnd.Next(controls.Length))
Loop While selectedControls.Contains(txt)
selectedControls.Add(txt)
txt.Text = (grade * 20 / 100).ToString()
Do
txt = controls(rnd.Next(controls.Length))
Loop While selectedControls.Contains(txt)
selectedControls.Add(txt)
txt.Text = (grade * 30 / 100).ToString()
Do
txt = controls(rnd.Next(controls.Length))
Loop While selectedControls.Contains(txt)
txt.Text = (grade * 10 / 100).ToString()
End If
击> <击> 撞击>
答案 1 :(得分:1)
单击按钮后,您需要将要交换/随机化/随机播放的值存储到List(Of T)
中,如下所示:
Dim ValuesToShuffle = New List(Of String)
ValuesToShuffle.Add(txtA.Text)
ValuesToShuffle.Add(txtB.Text)
ValuesToShuffle.Add(txtC.Text)
ValuesToShuffle.Add(txtD.Text)
现在,您将循环遍历值以进行随机播放并每次生成一个随机数并移动值,如下所示:
Dim rand = New Random()
For counter = 0 to ValuesToShuffle.Count- 1
Dim n = rand.Next(counter + 1)
Dim temp = ValuesToShuffle(counter)
ValuesToShuffle(counter) = ValuesToShuffle(n)
ValuesToShuffle(n) = temp
Next
最后,将洗牌后的值放回文本框中,如下所示:
txtA.Text = ValuesToShuffle(0)
txtB.Text = ValuesToShuffle(1)
txtC.Text = ValuesToShuffle(2)
txtD.Text = ValuesToShuffle(3)