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 trialDavid Debreceni
1,853 PointsCreating the MVP Challenge Question
"Can you please add a method called getTileCount that uses the for each loop you just leanred to loop through the characters and increment a counter if it matches? Return the count, please, thanks!" Following this, I cannot figure out how to write that if loop so that it doesn't find the character on every single for loop. Can anyone point me in the right direction? Thank you ahead of time.
public class ScrabblePlayer {
private String mHand;
public ScrabblePlayer() {
mHand = "";
}
public String getHand() {
return mHand;
}
public void addTile(char tile) {
// Adds the tile to the hand of the player
mHand += tile;
}
public boolean hasTile(char tile) {
return mHand.indexOf(tile) > -1;
}
public int getTileCount(char tile) {
int count = 0;
for(char letter: mHand.toCharArray()) {
if(mHand.indexOf(letter) >= 0) {
count++;
}
}
return count;
}
}
1 Answer
Craig Dennis
Treehouse TeacherWhat if you checked if tile
was equal to letter
in that loop?
David Debreceni
1,853 PointsDavid Debreceni
1,853 PointsThank you for that, I was completely over thinking it, but how does that variable letter work? Does the for loop re-write the value of letter every iteration?
Craig Dennis
Treehouse TeacherCraig Dennis
Treehouse TeacherYes exactly that! That is a for-each loop. So for each letter in the char array, it will run that code block, and letter will be set for that current loop.
David Debreceni
1,853 PointsDavid Debreceni
1,853 PointsOh okay, I think I was getting hung up on that part haha. Thanks!