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 (Retired) Delivering the MVP Determining if It Is Solved

tomtrnka
tomtrnka
9,780 Points

method isSolved() --- usage of .contains() instead of .indexOf()

Craig used the static method "indexOf()" to determine whether the answer is solved.

I always try to write the code before Craig does and then I compare the differences. In this case I can't really say if I'm right or not, cause this block of code works for me fine as well:

My code: public boolean isSolved() { return !getCurrentProgress().contains("-"); }

Craig's code: public boolean isSolved() { return !getCurrentProgress().indexOf('-') == -1 ; }

Can someone explain why should we use .indexOf() instead of .contains()?

Thanks

1 Answer

It is a matter of taste a preferences.

My code: public boolean isSolved() { return !getCurrentProgress().contains("-"); } here you are saying does whatever comes back from getCurrentProgress(). contains the character '-'. The answere will be true ot false and then you take action based on the boolean value.

Craig's code: public boolean isSolved() { return !getCurrentProgress().indexOf('-') == -1 ; } Here Craigs is asking ... does whatever string getCurrentProgress returns ... I am going to test if the character '-' is in the string ... recall ,,, string can be thought of as an array of chars ... so now MyString.indexOf('-') == -1 will return a boolean (T/F) ... which is essentially same thing as you had.

Again, which one is better ? It is a matter of taste a preferences. Hope this helps. If this answers your question, please mark the question as answered.