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 trialHenry Brenton
10,144 PointsHow to solve this by returning the result of an expression, rather than an if statement
Hello all,
Trying to solve this without using an if statement, as prompted by the challenge - I'm a bit stumped, and have tried a few things... not sure what I'm missing here!
Some advice would be much appreciated,
Many Thanks
Henry
public class ScrabblePlayer {
// A String representing all of the tiles that this player has
private String tiles;
public ScrabblePlayer() {
tiles = "";
}
public String getTiles() {
return tiles;
}
public void addTile(char tile) {
tiles += tile;
}
public boolean hasTile(char tile) {
boolean isIN = tiles.indexOf(tile) != -1;
if (isIN) {
return true;
} else {
return false;
}
}
}
1 Answer
Jennifer Nordell
Treehouse TeacherHi there, Henry Brenton ! Looks to me like you're doing great! Lots of students get stuck on this so you're not alone. When programming you can return the result of an evaluation directly. Ideally, you never want to see a setup where if this is true return true, otherwise, return false.
Here's an example. Let's say we're going to return true if x
is greater than 100 and false if it's 100 or less:
if(x > 100) {
return true;
} else {
return false;
}
There is nothing wrong with the above code and will do what is expected. But it's a rather verbose way to go about it. Let's try returning the result of the evaluation directly:
return x > 100;
There you have it. Nice and short, right? The evaluation x > 100
will run and return a boolean from the evaluation which we then immediately return.
Hope this helps!
Henry Brenton
10,144 PointsHenry Brenton
10,144 PointsHi Jennifer, thank you for your help! Very informative and much appreciated!
Henry