储物柜阵列程序VISUAL BASIC

时间:2015-01-03 19:09:36

标签: vb.net

我必须在Visual Basic中执行一个程序,它显示使用布尔数组打开或关闭100个储物柜的状态。单击按钮Initialize后,所有储物柜的状态均为opened,但单击Simulate时,会关闭每个第N个储物柜(每个第二个储物柜,然后是每个第三个储物柜,然后是每个第四个储物柜,依此类推。)

我让它工作,所以它总是为每个储物柜显示opened,但我无法弄清楚如何让它关闭每个第N个储物柜。

这是我的代码:

Public Class Form1  
    Dim index As Integer  
    Dim doors(100) As Boolean

    Private Sub btnInitialize_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnInitialize.Click

        Dim count As Integer
        lstLockers.Items.Clear()
        lstLockers.Items.Add("Locker" & vbTab & "Status")

        For count = 1 To 100
            doors(count) = True

            If doors(count) = True Then
                lstLockers.Items.Add(count & vbTab & "Opened")
            End If
        Next

    End Sub



    Private Sub btnSimulate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSimulate.Click

        lstLockers.Items.Clear()
        lstLockers.Items.Add("Locker" & vbTab & "Status")

        Dim count As Integer
        Dim eq As Integer

        For count = 1 To 100
            doors(count) = True

            If doors(count) = True Then
                lstLockers.Items.Add(count & vbTab & "Opened")
            ElseIf doors(count) = False Then
                lstLockers.Items.Add(count & vbTab & "Closed")
            End If


        Next



    End Sub
End Class

1 个答案:

答案 0 :(得分:0)

btnSimulate_Click方法中,您将doors索引设置为true,然后立即检查是否为真。这就是为什么它总是说opened

关于关闭每个第N个储物柜,你可以用一个简单的计数器变量来完成。

' n represents the "Nth" locker to close.
Dim n As Integer = 2
Dim progress As Integer = 0 ' Progress to n.

For count = 1 To 100
    ' This line shouldn't be here. doors has already been initialized.
    'doors(count) = True

    ' Increment progress towards n.
    progress = progress + 1

    ' Check if Nth interval is reached.
    If n = progress Then
        ' It is. Close the locker.
        doors(count) = False
        ' Increment n and reset the progress counter.
        n = n + 1
        progress = 0
    End If

    If doors(count) = True Then
        lstLockers.Items.Add(count & vbTab & "Opened")
    ElseIf doors(count) = False Then
        lstLockers.Items.Add(count & vbTab & "Closed")
    End If

Next

这会关闭储物柜:

  • 2(n = 2)
  • 5(n = 3)
  • 9(n = 4)
  • 14(n = 5)