Oisin O'Connor
Oisin O'Connor

Reputation: 11

I am unsure about how to count how many times certain conditions are met

I am building a program in Visual Studio that is a "Guess the Word" game.

What happens is, my array generates a Word, and an input box appears. The user has to guess that word by entering text into the input box, and if it is right a message box will show well done, and if not, a message box will appear saying try again.

I need a function that will count how many words the user guesses right. I have this, but if the word is equal to the users input, 1 will appear in the label I set it to appear in, and if it isn't equal to it, a 0 will appear. This code worked (with different variables etc.) when I was counting the amount of times a certain button was clicked, so I'm confused about why it's not working now.

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

where word is the word generated by my array.

Why is the above code not incrementing the number of correct guesses?

Upvotes: 0

Views: 101

Answers (2)

Bozhidar Stoyneff
Bozhidar Stoyneff

Reputation: 3634

As the others suggested, initialize the hits variable at the point of declaration and get rid of the assignment line:

Static hits As Integer = 0 ' Modify the declaration like this line
' hits = 0 - remove this line

Another solution is to have the hits variable declared at a module level, in which case the Static keyword is not necessary:

Private hits As Integer = 0

Then access it wherever you like in your code and rest assured that its value is preserved between calls to your methods. In any case, you need to make sure, that this line is gone:

hits = 0

Upvotes: 0

Andrew Morton
Andrew Morton

Reputation: 25013

It goes wrong because you have

Static hits As Integer
hits = 0

which means that hits is set to 0 each time it executes the line hits = 0.

If instead you use

Static hits As Integer = 0

then it will initialise it to 0, and it will do that only once.

Upvotes: 1

Related Questions