Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Creating the MVP Prompting for Guesses

tiago goncalves
tiago goncalves
1,912 Points

why isn't letter 't' the index 0?

public class Hangman {

    public static void main(String[] args) {
        // Enter amazing code here:

      Game game = new Game("treehouse");
      Prompter prompter = new Prompter(game);
      boolean isHit = prompter.promptForGuess();
      if(isHit){
      System.out.println("We got a hit");
      } else{
      System.out.println("Whoops missed");
      }

    }

}

import java.io.Console; //packages

public class Prompter{
  private Game mGame;

  public Prompter(Game game){

    mGame = game;
  }

  public boolean promptForGuess(){
  Console console = System.console();
  String guessAsString = console.readLine("Enter a letter: ");

    char guess = guessAsString.charAt(0);
    return mGame.applyGuess(guess);
  }

2 Answers

Allan Clark
Allan Clark
10,810 Points

It is, I got a Hit when running this code and guessing t.

Rachelle Wood
Rachelle Wood
15,362 Points

The code can be confusing since when you put in the repl example given by the instructor, charAt(index) searches the string for the right letter at the right index number but using charAt(0) in the code above not only returns 't' as a hit but in fact does so if you type in any of the letters that belong to the string "treehouse". In fact, if you put any other number in the parameter of charAt(0) in the code above, you will break the game and get an exception when you try to type in a letter. This seems counterintuitive until you realize that the player is expected to type one letter when prompted for it. Since the length of a letter is only 1 character long and as a result always has an index number of 0, you have to use charAt(0). I hope this clears this up a bit since I was stumped on this one for a while too.

tiago goncalves
tiago goncalves
1,912 Points

thank you for your answer guys. :)

Benjamin Gooch
Benjamin Gooch
20,367 Points

Glad someone asked about this and that you answered so well! I was a bit confused about the charAt(0) as well. If I understand correctly, you're not asking for the index of 0 from "treehouse", but instead the index of 0 from the character input by the user.

Is that correct?