如何在VB.Net中获得适当增量的计数器变量

时间:2014-08-31 20:38:54

标签: vb.net variables scope

我有一个问题,在测试中,它没有成功。我的代码用于检查是否输入了正确答案的按钮。如果答案是正确的,标签上会有一条消息;相反,如果错了就会有消息。​​

我想到的是有一个变量来检查是否输入了错误的输入“3次”然后让我的代码在标签中显示。这就是我所拥有的:

Private Sub btnAnswer_Click(sender As Object, e As EventArgs) Handles btnAnswer.Click

    'Setup count variable to monitor wrong answer count.
    Dim CounterWrong As Integer = 1

    If (txtSpell.Text = "Bicycle") And (CounterVar = 0) Then
        lblAnsResult.Text = "Correct!"
        lblAnsResult.Show()
        btnNext.Focus()

    ElseIf (txtSpell.Text = "Table") And (CounterVar = 1) Then
        lblAnsResult.Text = "Correct!"
        lblAnsResult.Show()
        btnNext.Focus()

    ElseIf (txtSpell.Text = "Television") And (CounterVar = 2) Then
        lblAnsResult.Text = "Correct!"
        lblAnsResult.Show()
        btnNext.Focus()

    Else
        CounterWrong += 1
        txtSpell.Text = String.Empty
        lblAnsResult.Text = "Wrong! Try Again..."
        lblAnsResult.Show()
        txtSpell.Text = Focus()

    End If

    While CounterWrong < 3
        CounterWrong += 1

        If CounterWrong = 5 Then
            MessageBox.Show(CounterWrong)
        End If
    End While

End Sub

我尝试设置我的小While循环以查看我的CounterWrong变量是否正常递增,但我想不出如何设置它。我知道每次点击按钮,CounterWrong都会被设置为1.有人可以让我在正确的方向上找到我吗?感谢。

2 个答案:

答案 0 :(得分:2)

将计数器更改为VB&#39;静态&#39;变量:

Static CounterWrong As Integer = 0

或使用班级字段:

Private CounterWrong As Integer = 0

VB&#39;静态&#39;变量维护方法调用之间的状态(C ++有类似的功能)。 许多人会认为使用某个领域是更好的做法。

我也将它们改为&#39; 0&#39;最初 - 我认为这更有意义。

答案 1 :(得分:2)

您可以在表单上声明变量:

Public Class frmTest

    'Setup count variable to monitor wrong answer count.
    Dim CounterWrong As Integer = 1


    Private Sub btnAnswer_Click(sender As Object, e As EventArgs) Handles btnAnswer.Click

        If (txtSpell.Text = "Bicycle") And (CounterVar = 0) Then
            lblAnsResult.Text = "Correct!"
            lblAnsResult.Show()
            btnNext.Focus()

        ElseIf (txtSpell.Text = "Table") And (CounterVar = 1) Then
            lblAnsResult.Text = "Correct!"
            lblAnsResult.Show()
            btnNext.Focus()

        ElseIf (txtSpell.Text = "Television") And (CounterVar = 2) Then
            lblAnsResult.Text = "Correct!"
            lblAnsResult.Show()
            btnNext.Focus()

        Else
            CounterWrong += 1
            txtSpell.Text = String.Empty
            lblAnsResult.Text = "Wrong! Try Again..."
            lblAnsResult.Show()
            txtSpell.Text = Focus()

        End If

        If CounterWrong = 5 Then
            MessageBox.Show(CounterWrong)
        End If

    End Sub
End Class