0

所以这只是我的问题VB.Net 成绩分布练习的延续

但是我现在想做的是在按钮单击时交换或随机化它们的位置。

所以这就是我正在做的事情:

    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 事件上

但我真的不知道如何随机化他们的位置。有任何想法吗?谢谢。

4

2 回答 2

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 Grade As Double Dim rnd = New Random() Dim controls = {txtA, txtB, txtC, txtD} Dim selectedControls = New List(Of Control) 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

于 2013-07-25T14:41:16.010 回答
1

单击按钮后,您需要将要交换/随机化/随机播放的值存储到 aList(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)
于 2013-07-25T14:48:00.993 回答