Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Creating the MVP Storing Guesses

Jasper Kop
Jasper Kop
9,058 Points

Why are have you chosen to use the statement answer.indexOf(letter) != -1 instead of answer.indexOf(letter)== 0?

Why are have you chose to use the statement : answer.indexOf(letter) != -1 instead of answer.indexOf(letter)== 0?

I understand the block of code but it feels like there is a reason to it, that I don't understand yet.

1 Answer

emiliet
emiliet
10,401 Points

The statement

answer.indexOf(letter) != -1

will evaluate as true if the character is present in the answer.

This is because the indexOf method will return the first index of the given character. If the given character is not present, it will return -1.

The statement

answer.indexOf(letter) == 0

will evaluate as true only if the given character has an index of 0 in the answer (meaning it is the first character).