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 Current Progress

Prabha Gani
Prabha Gani
627 Points

Why can't I use == to check equality?

The way I understand this code: if (hits.index.Of(letter) != -1 { display = letter; }

is that, if letter matches the value in hits, then display=letter. How come I cannot instead use the == to check if letter matches the value in hits. For eg. if (letter == hits.charAt(0)) { display = letter; }

you can do it but it will require additional for loop for iterating through all characters of String hits check this out- \ public String getCurrentProgress() { String progress = ""; for(char letter : answer.toCharArray()) { char display = '-' ;
for(char hitletter : hits.toCharArray()) { if(letter==hitletter) { display = letter; break; }


progress +=display; } return progress; } \

1 Answer

28,526 Points

The reason is that your understating is off.

The indexOf (not index.of) method checks whether a character or string is present somewhere in the thing it is called on. If it is present somewhere then it returns the index where the character is, if it is not present then it returns -1.

That means that if I had code like this for example: "Hello".indexOf("o") it would return 4 since the letter o is present at index 4 of that string. If I had this code: "Hello".indexOf("a") then it would return -1 because the letter a is not present anywhere in the string.

So in the code example you post the code checks if the letter is present somewhere in the hits string, it does not check if letter and hits contain exactly the same thing, which the == operator would do.

Prabha Gani
Prabha Gani
627 Points

Ahh i see, i get it now. Thanks :-)