1

我必须想出一个程序来随机改变文本框中的名称。我已经把所有的东西都弄到了名字随机变化的地步。它只移动一次,但我的消息框在代码中出现的次数与单击确定后名称应移动的次数一样多。有谁知道为什么循环不适用于名称转换。我在想也许消息框需要控制循环,但我无休止地搜索,找不到怎么做。任何建议或推荐到其他网站将非常感谢。我的代码如下。

公开课形式1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim RandomNumber As Integer
    Dim min, max As Integer
    Dim temp, temp2, temp3, temp4, temp5, temp6 As String
    Dim i As Integer

    min = 3
    max = 11

    Randomize()
    RandomNumber = Int((max - min + 1) * Rnd() + min)

    temp = n1.Text
    temp2 = n2.Text
    temp3 = n3.Text
    temp4 = n4.Text
    temp5 = n5.Text
    temp6 = n6.Text

    For i = 0 To RandomNumber - 1
        n1.Text = temp6
        n2.Text = temp
        n3.Text = temp2
        n4.Text = temp3
        n5.Text = temp4
        n6.Text = temp5
        MessageBox.Show("Shift " & i & " of " & RandomNumber & " complete")
    Next

End Sub

结束类

4

3 回答 3

2

认为临时变量也应该在循环中

For i = 0 To RandomNumber - 1

temp = n1.Text
temp2 = n2.Text
temp3 = n3.Text
temp4 = n4.Text
temp5 = n5.Text
temp6 = n6.Text  

    n1.Text = temp6
    n2.Text = temp
    n3.Text = temp2
    n4.Text = temp3
    n5.Text = temp4
    n6.Text = temp5
    //MessageBox.Show("Shift " & i & " of " & RandomNumber & " complete")
Next

更新

您也可以使用一个临时变量以这种方式执行此操作

For i = 0 To RandomNumber - 1

  temp = n6.Text

  n6.Text = n5.Text
  n5.Text = n4.Text
  n4.Text = n3.Text
  n3.Text = n2.Text
  n2.Text = n1.Text
  n1.Text = temp

Next
于 2012-11-12T22:55:53.093 回答
0

在 MessageBox 之前或之后添加这一行:

Application.DoEvents
于 2012-11-12T22:56:52.493 回答
0

像codingbiz建议的那样将临时变量的赋值放在循环中会使其工作,但您根本不需要循环。如果将字符串放入数组中,则可以计算它们的位置:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  Dim RandomNumber As Integer
  Dim min, max As Integer
  Dim temp As New String(5)

  min = 3
  max = 11

  Randomize()
  RandomNumber = Int((max - min + 1) * Rnd() + min)

  temp(0) = n1.Text
  temp(1) = n2.Text
  temp(2) = n3.Text
  temp(3) = n4.Text
  temp(4) = n5.Text
  temp(5) = n6.Text

  n1.Text = temp((0 + RandomNumber) Mod 6)
  n2.Text = temp((1 + RandomNumber) Mod 6)
  n3.Text = temp((2 + RandomNumber) Mod 6)
  n4.Text = temp((3 + RandomNumber) Mod 6)
  n5.Text = temp((4 + RandomNumber) Mod 6)
  n6.Text = temp((5 + RandomNumber) Mod 6)

End Sub
于 2012-11-12T23:01:01.070 回答