Search code examples
vb.netvisual-studio-2010visual-studioloopsmessagebox

VB looping complication


I have to come up with a program that shifts names in a text box a random amount of times. I have gotten everything up to the point where the names shifts a random amount of times. It only shifts its once, but my messagebox appears through the code as many times as the names should be shifting once i click ok. Does anyone know why the loop is not working for the name shifts. I was thinking maybe the messagebox needs to control the loop, but I have searched endlessly and cannot find how that would be done. Any suggestions or referrals to other sites would be nice thanks. My code is below.

Public Class Form1

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

End Class


Solution

  • Think the temp variables should also be in the loop

    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
    

    UPDATE

    You can also do it this way using one temp variable

    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