Sam
Sam

Reputation: 59

Java: Guessing Game error count

Hey guys (I'm New to java B.T.W.)

I am developing a small guessing game using Java and I've been stuck in some problem. I'd really appreciate if anyone can help me to overcome this problem.

The game is something like this:

Now my problem is I've been stuck with the error count...

My code is something like this:

 //word is the word that user must guess
 // asciiToChar is letter that users've guessed
 // J is just a variable used for count

 for (j=0; j < word.length(); j++)
       {    if (word.charAt(j) != asciiToChar)
            {
             error++;
            }
       }
 System.out.println("Number of Errors: "+" "+ error);

Everytime the users perform a wrong guess the error count is supposed to be increased but it's showing some random numbers like 8,14 or something. I need to figure it out on how to increase the count by only one until 5 guesses

And whenever I use word.charAt(j) != asciiToChar instead of == It's giving me a right count for correct guesses.

I can't figure it out :(

Any help would be apprecited

Upvotes: 2

Views: 570

Answers (2)

MightyPork
MightyPork

Reputation: 18861

Your loop logic is wrong, it adds error for every single character that doesnt equal the user guess.

Try to do it like this (if I got it right):

boolean found = false;
for (j=0; j < word.length(); j++)
{    
    if (word.charAt(j) == asciiToChar)
    {
        found = true;
        break; // no need to search further
    }
}
if(!found) error++; // if the letter isn't used, add 1 error

As rightfully pointed out by Ingo Bürk in the comments, there's a pre-baked solution for this:

if(!word.contains(asciiToChar)) { error++; }

Upvotes: 1

kviiri
kviiri

Reputation: 3302

Your loop goes through all the characters in word and for each character that doesn't match the one given by the user, it increases errors by one. So if the word is "cat" and the user guesses 'a', you'll get two errors, one for 'c' and one for 't'.

Upvotes: 1

Related Questions