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 trialJames Croxford
12,723 PointsClarification on the 2nd task from the Scrabble Challenge
Hi everyone,
I have managed to complete the second part of the challenge following on from Storing Guesses, based around scrabble tiles.
The code that I eventually worked out from fiddling around and also reading past questions was:
return tiles.indexOf(tile) != -1;
I suppose I am just asking for a bit of understanding as to why this answer is so simple, compared to my first inclination of expanding the boolean involving say an else element, along the lines of:
public boolean hasTile(char tile) {
// TODO: Determine if user has the tile passed in
return tiles.indexOf(tile) !=-1;
else return false
I presume this is because the use of a boolean means that the language knows that if the tile returns an index which is infact equal to -1, then the only outcome must indeed be false, negating the need for any further code to stipulate what to do? Although then (and this is probably getting well beyond the point of this task) if you wanted to leave a message to the player 'you already have this tile passed in' would you then need to stipulate what happens when the boolean returns false to print that message to the player?
2 Answers
Brendon Butler
4,254 PointsYou will never be able to have one return statement after another. Since the first one will always be called and then the method will close. You could wrap the return methods in if statements, but you would still need a return statement at the end of the method somewhere.
Since you're checking a conditional, tiles.indexOf(tile) != -1
. It's going to return a true or false value. This line is checking to see if the index of a specific tile is not equal to negative one. If it is not equal to negative one, return true. Else, return false. It does this all in one line.
else
statements are only valid if appended to the end of an if statement body. Having this else statement there would actually break your code and prevent compiling. Since you're checking the conditional in your return, you do not need an if statement in this case.
James Croxford
12,723 PointsThat's really cleared it up for me! Thank you!