Search code examples
javacharstringbuffercharat

Java - Hangman Game - trouble with charAt on StringBuffer variable


So I am trying to make a hang man game using a website that returns random word. I'm using that random word for the hangman game.

What I am stuck on is validating a guess the user makes. Here is the code, I am just putting everything in main first then making separate methods to do the work for me after this works.

public static void main(String[] args) throws Exception {
    randomWord = TestingStuff.sendGet();
    int totalTries = 1;
    char[] guesses = new char[26];
    int length = randomWord.length();
    Scanner console = new Scanner(System.in);

    System.out.print("* * * * * * * * * * * * * * *"
            + "\n*    Welcome to Hangman!    *"
            + "\n* * * * * * * * * * * * * * *");
    System.out.println("\nYou get 10 tries to guess the word by entering in letters!\n");
    System.out.println(randomWord);
    /*
     Cycles through the array based on tries to find letter
     */
    while (totalTries <= 10) {
        System.out.print("Try #" + totalTries);
        System.out.print("\nWhat is your guess? ");
        String guess = console.next();
        char finalGuess = guess.charAt(0);
        guesses[totalTries - 1] = finalGuess; //Puts finalGuess into the array


            for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
                if (finalGuess != guesses[i]) {
                    for (int j = 0; i < length; j++) { //scans each letter of random word
                        if (finalGuess.equals(randomWord.charAt(j))) {

                        }
                    }
                } else {
                    System.out.println("Letter already guessed, try again! ");
                }
            }
        }
    }

What I am stuck on is inside of the while loop where it says:

            for (int i = 0; i < totalTries; i++) { //checks to see if the letter is already guessed
                if (finalGuess != guesses[i]) {
                    for (int j = 0; i < length; j++) { //scans each letter of random word
                        if (finalGuess.equals(randomWord.charAt(j))) {

                        }
                    }
                } else {
                    System.out.println("Letter already guessed, try again! ");
                }
            }

It is giving me an error saying "char cannot be dereferenced". Am I missing something here?


Solution

  • finalGuess is a primitive char - you can't use methods, such as equals on it. You could just compare the two chars using the == operator:

    if (finalGuess == randomWord.charAt(j)) {