如何使用循环实现RandomSwitch()函数?

时间:2018-03-29 06:00:44

标签: vb.net

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    If PictureBox1.Visible = True Then 'if picture box 1 is visible (initially visible) then
        PictureBox1.Visible = False 'picture box 1 is hidden and
        PictureBox2.Visible = True 'picture box 2 is visible (initially hidden)
        Label1.Text = "OFF" 'label reads that the light is OFF (initially reads ON)
    ElseIf PictureBox2.Visible = True Then 'if picture box 2 is visible then
        PictureBox2.Visible = False 'picture box 2 is hidden and
        PictureBox1.Visible = True 'picture box 1 is visible
        Label1.Text = "ON" 'label reads that the light is ON
    End If

End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    Application.Exit() 'closes the form

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Dim generator As New Random


    Do

        If PictureBox1.Visible = True Then 'if picture box 1 is visible (initially visible) then
        PictureBox1.Visible = False 'picture box 1 is hidden and
        PictureBox2.Visible = True 'picture box 2 is visible (initially hidden)
        Label1.Text = "OFF" 'label reads that the light is OFF (initially reads ON)
    ElseIf PictureBox2.Visible = True Then 'if picture box 2 is visible then
        PictureBox2.Visible = False 'picture box 2 is hidden and
        PictureBox1.Visible = True 'picture box 1 is visible
        Label1.Text = "ON" 'label reads that the light is ON
    End If

End Sub

结束班

1.如何使按钮2执行按钮1所做的操作,但它必须选择多次随机执行。限制是1-20倍。

1 个答案:

答案 0 :(得分:0)

以下是如何使用Random类的代码。唯一的麻烦是循环执行速度太快,以至于你不会看到任何东西。

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim rnd As New Random
        Dim NumberOfLoops = rnd.Next(1, 21)
        'The returned Integer will be equal to or more than 1 and less than 21
        Dim Counter As Integer = 1
        Do
            If PictureBox1.Visible = True Then
                Label1.Text = "On"
            Else
                Label1.text = "Off"
            End If
            PictureBox1.Visible = Not PictureBox1.Visible
            PictureBox2.Visible = Not PictureBox2.Visible
            Counter += 1
        Loop While NumberOfLoops <= Counter

End Sub