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 trialMacLorand Mushiva
5,419 PointsEvery thing in my code seems to be perfect. I'm suspicious of the 'return count' text, I get 1 match instead of 2.
Please help
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 x: mHand.toCharArray())
{ if (mHand.indexOf(tile)>-1)
{
count++;
return count;
}
}
return count;
}
}
1 Answer
Dan Johnson
40,533 PointsindexOf will return the position of a character in a string. Because of this, if tile happens to exist in mHand then every single iteration will result in the if
conditional passing even if there was only one occurrence in mHand.
The reason you'd get 1 as the count was, as you suspected, the inner return statement. When you hit a return statement you immediately exit the method so count would never be able to exceed 1.
So in order to check for the count of how many times a tile occurs we can do the following:
- Iterate through all the characters in mHand as you were doing.
- Check for equality against tile and the current character (x in the case of your original code).
- Increment count if they are equal.
- Return count after completely iterating through mHand.