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 Creating the MVP Storing Guesses

shu Chan
shu Chan
2,951 Points

What does return isHit do specifically?

I'm not too clear as to what it actually does in this code

1 Answer

Anders Björkland
Anders Björkland
7,481 Points

Hi shu Chan!

So if I understand you correctly you are asking about this code here:

public boolean applyGuess(char letter) {
    boolean isHit = answer.indexOf(letter) != -1; 
}
// answer is a String that stores the correct answer, of which the player tries to guess at.

isHit simply stores the result of answer.indexOf(letter) != -1; What this does is looking for the specific letter in the answer-String. indexOf(char c) is a method of the String class and returns the index (the position in the String) of the first letter that is found that corresponds with the char that was passed to the method. If you have this:
String veggie = "cucumber";
int indexOfC = veggie.indexOf('c');
System.out.println(indexOfC );

The output would be 0 since 'c' is found at the first position in the String. If we expand on the example with the following:
int indexOfZ = veggie.indexOf('z');
System.out.println(indexOfZ);
The output would be -1. The letter is not present in the veggie variable, and in such a case the method will return -1 to show that it is not in any position of the String.

So, if the value of index is not -1, this would mean that a letter is present in the String. boolean isHit = answer.indexOf(letter) != -1; will assign true to the boolean isHit if the guess letter is in fact in the String answer, and false if it is not.

I hope this answers you question. If you need more, just ask.

Good luck!