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 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,558 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 :-)