我正在Visual Studio中构建一个程序,这是一个"猜猜词"游戏。
会发生什么,我的数组生成一个Word,并出现一个输入框。用户必须通过在输入框中输入文本来猜测该单词,如果它是正确的,则消息框将显示完成,如果没有,则会出现一个消息框,说再试一次。
我需要一个能够计算用户猜对的字数的函数。我有这个,但如果单词等于用户输入,1将出现在我设置它出现的标签中,如果它不等于它,则会出现0。当我计算点击某个按钮的次数时,这段代码(使用不同的变量等)起作用,所以我很困惑为什么它现在不起作用。
Dim guess As String
guess = (LCase(InputBox("What is the word", "Guess the word")))
Static hits As Integer
hits = 0
If word = guess Then hits += 1
Label8.Text = hits
其中word
是我的数组生成的单词。
为什么上面的代码没有增加正确的猜测次数?
答案 0 :(得分:1)
它出错了,因为你有
Static hits As Integer
hits = 0
表示每次执行hits
行时hits = 0
都设置为0。
如果您使用
Static hits As Integer = 0
然后它将它初始化为0,它只会执行一次。
答案 1 :(得分:0)
正如其他人所建议的那样,在声明点初始化hits
变量并删除赋值行:
Static hits As Integer = 0 ' Modify the declaration like this line
' hits = 0 - remove this line
另一种解决方案是将hits
变量声明为module level,在这种情况下,Static
关键字不是必需的:
Private hits As Integer = 0
然后在代码中的任何位置访问它,并确保在调用方法之间保留其值。 无论如何,你需要确保这条线不见了:
hits = 0