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

Jasper Kop
Jasper Kop
10,423 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).