user6210747
user6210747

Reputation:

How do you compare characters to characters in a word? (Java)

I'm trying to compare the character that the user enters to the randomly generated word to see if it matches or not... what can i use to compare them?

    if (playerChoice.equals(g.originalWord.charAt(7))) { //
        g.revealHiddenLetter(); 
    }       
    else  {
        System.out.println(g.guessThisWord);
        guesses--;// if player is wrong they lose a guess
        System.out.println("Guesses Left: " + guesses);
    }

Upvotes: 1

Views: 876

Answers (3)

Adam
Adam

Reputation: 36743

An easier way to solve this is just to convert the character to a String of length 1 and use the existing String.contains() method

char guess = 'h';
String originalWord = "hello";
System.out.println(originalWord.contains(Character.toString(guess)));

Upvotes: 0

theVoid
theVoid

Reputation: 743

To compare Characters you use the == symbol not the equals() method, since in java Characters are represented as integers.So what you want to do can be achived as follows:

 if (playerChoice == g.originalWord.charAt(7)) { //
    g.revealHiddenLetter(); 
 }       
 else  {
     System.out.println(g.guessThisWord);
     guesses--;// if player is wrong they lose a guess
     System.out.println("Guesses Left: " + guesses);
 }

Upvotes: 1

NDizzle
NDizzle

Reputation: 24

Iterate over the characters in the hidden word, you could use a method such as:

private boolean charInWord(char playerChoice) {
    for(int i = 0; i < originalWord.length(); i++) {
            if(originalWord.charAt(i) == playerChoice) {
                return true;
            }
        }
    return false;
}

This will return true if the letter exists within the hidden word.

Upvotes: 0

Related Questions